我無法弄清楚如何在form_for中正確寫入一個url路徑來創建一個新對象。我試圖以不同的方式做,但沒有運氣。我想有一些特定形式的url可以包含對象的id。 form_for helper中的路徑不正確
視圖/任務/ 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 %>
耙路由
控制器/ 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
的意見/任務/ 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>
有人能幫忙嗎?
試試這個:'<%= form_for [@ task.user,@task] do | f | %>' – Deep
@Deep相同的錯誤 –
僅使''%= form_for @task,url:new_user_task_path(@ task.user)do | f | %>' – Deep