【问题标题】:UrlGenerationError in Rails AppRails 应用程序中的 UrlGenerationError
【发布时间】: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


【解决方案1】:

toggle_completed ex-创建单独的路由-

 put 'list/task/:id', to: 'tasks#toggle_completed', as: :list_task_completed

<%= link_to('Toggle', list_task_completed_path(:id => task.id), :method => :put ) %>

【讨论】:

  • list_task_completed_path 如果这不是您的路线,您可以通过运行命令rake routes | grep toggle_completed在您的路线中搜索自己的路线
  • 感谢您的帮助!我用新路由添加了你的代码,但我仍然收到 URLGenerationError: No route matches {:action=>"toggle_completed", :controller=>"tasks", :id=>nil} missing required keys: [: id]
  • 对不起,我的错误我已经改变了答案,而不是写进路线。请试试这个
猜你喜欢
  • 2015-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2017-03-29
  • 1970-01-01
  • 1970-01-01
  • 2015-12-30
相关资源
最近更新 更多