我不知道如何正确地在form_for中编写一个url路径来创建一个新对象。我尝试用不同的方式来做,但是没有运气。我想URL的某种特殊形式可以包括对象的ID。
views / tasks / new.html
<%= form_for :task, url: [@task.user, @task] do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :description %><br>
<%= f.text_area :description %>
</p>
<p>
<%= f.hidden_field :user_id, value: params[:user_id] %>
<%= f.submit %>
</p>
<% end %>
耙路
controllers / tasks_controller.rb
class TasksController < ApplicationController
before_filter :authorize, only: [:edit, :new, :destroy]
def index
@tasks = Task.where(user_id: params[:user_id])
end
def show
@task = Task.find(params[:id])
redirect_to users_path
end
def edit
@task = Task.find(params[:id])
end
def new
@task = Task.new
end
def create
@task = Task.new(task_params)
if @task.save
redirect_to @task
else
render 'new'
end
end
def update
@task = Task.find(params[:id])
if @task.update(task_params)
redirect_to @task
else
render 'edit'
end
end
def destroy
@task = Task.find(params[:id])
@task.destroy
respond_to {|format| format.js }
end
private
def task_params
params.require(:task).permit(:title, :description)
end
end
views / tasks / index.html
<p align="right"><%= link_to 'Users', users_path %> <%= link_to 'Tasks', user_tasks_path %></p>
<h3>Tasks database</h3>
<table>
<% @tasks.each do |task| %>
<tr id="task_<%= task.id %>">
<td>
<b>Title:</b>
<i> <%= task.title %></i>
</td>
<td>
<b>Description: </b>
<i><%= task.description %></i>
</td>
<td>
<%= link_to 'Edit', edit_user_task_path(task.user, id: task.id) %>
</td>
<td>
<%= link_to 'Delete', user_task_path(task.user, id: task.id),
data: { confirm: 'Are you sure?' }, :method => :delete, remote: true %>
</td>
</tr>
<% end %>
<tr>
<td><%= link_to 'Create task', new_user_task_path %></td>
<td><%= link_to 'Back to Users', users_path %></td>
</tr>
</table>
有人可以帮忙吗?
最佳答案
您为nested_routes
和tasks
设置了users
,因此按如下所示更改form_for
应该可以解决您的问题
<%= form_for [current_user, @task] do |f| %>
关于ruby-on-rails - form_for帮助器中的路径不正确,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31504275/