【发布时间】:2017-11-02 09:47:48
【问题描述】:
我搜索了这个站点并询问了其他几个程序员,但无法弄清楚我的代码有什么问题。我是 Rails 的初学者,所以我仍在努力解决所有问题。
我收到此错误:
列表中的ActionController::UrlGenerationError#show
没有路由匹配 {:action=>"toggle_completed", :controller=>"tasks", :id=>nil, :list_id=>3} 缺少必需的键:[:id]
这是它在 Lists#show 页面上引用的代码:
<p id="notice"><%= notice %></p>
<h3>add a task</h3>
<%= render 'tasks/form', task: Task.new() %>
<p>
<strong>List Name:</strong>
<%= @list.name %><p></p>
<% @list.tasks.each do |task| %>
<td><%= task.id %></td>
<td><%= task.name %></td>
<td><%= task.completed %></td>
<td><%= link_to('Toggle', toggle_completed_list_task_path(:list_id => @list.id,
:id => task.id), :method => :put ) %></td><br />
<% end %>
</p>
我的路线:
resources :lists do
resources :tasks do
member do
put :toggle_completed
end
end
end
任务控制器:
def toggle_completed
@task = Task.find(params[:id])
@task.completed = !@task.completed
@task.save
end
列出 has_many:任务 和 任务belongs_to:列表
我在我的 Lists#show 页面上做了一些实验,如果我添加了这一行:
<%= task.id %>
正确的值出现在页面上,所以我不确定为什么它会显示为 nil。我已经搜索了该站点,但没有找到任何真正讨论这个确切问题的内容。谢谢!
【问题讨论】:
-
您是否有机会在 show action 中创建
list.tasks的任何新实例 -
因为在这种情况下,您将在
@list.tasks中获得一个新的初始化实例,而没有id -
你好迪帕克。我不知道。我在该页面上确实有一个用于创建新任务的表单。我将编辑原始帖子并添加整个 show.html.erb 页面中的代码
-
Deepak,我想你已经弄清楚问题所在了。在我的 Lists#show 页面上,我正在呈现一个表单,在该表单上,我正在使用@list.tasks.build。我认为这是在初始化实例,所以这是有道理的!非常感谢!
-
很高兴它有帮助:)
标签: ruby-on-rails url null