【问题标题】:Nested Resources - UrlGenerationError - No route matches嵌套资源 - UrlGenerationError - 没有路由匹配
【发布时间】:2015-08-06 16:10:15
【问题描述】:

我正在开发一个基本的 Rails 应用程序。为了让事情顺利进行,我创建了两个脚手架。

  • 日历
  • content_items

然后我创建了适当的关联。

app/models/calendar.rb

class Calendar < ActiveRecord::Base
   has_many :content_items
end

app/models/content_item.rb

class ContentItem < ActiveRecord::Base
  belongs_to :calendar
end

routes.rb

resources :calendars do
  resources :content_items
end

但是,现在当我尝试查看特定日历的 content_items 时,出现以下错误:

ActionController::UrlGenerationError - 没有路由匹配 {:action=>"show", :calendar_id=>nil, :controller=>"content_items", :id=>"5"} 缺少必需的键:[:calendar_id]

它说错误来自: views/content_items/index.html.erb

<td><%= link_to 'Show', calendar_content_item_path(content_item.calendar, content_item) %></td>

我尝试了几种不同的路线,但它们会导致不同的错误。自从我创建了嵌套路由后,是否需要更新模型和/或控制器?

【问题讨论】:

  • 基本上,rails 无法仅从 content_item 对象生成 url。由于它是嵌套的,因此您还需要传递父日历对象。检查documentation

标签: ruby-on-rails ruby-on-rails-4 nested-routes


【解决方案1】:

您忘记在路由中添加_path 后缀:

<td><%= link_to 'Show', content_items_path(calendar) %></td>

【讨论】:

  • 导致这个:未定义的局部变量或方法`content_item_path'
  • + 忘记使用复数形式:content_items_path
  • +忘记传递calendar变量来识别相关日历
【解决方案2】:

尝试使用

&lt;td&gt;&lt;%= link_to 'Show', calendar_content_item_path(content_item.calendar, content_item) %&gt;&lt;/td&gt;

【讨论】:

  • 试过这个。我认为它更接近。更新了原始帖子中的代码和错误。
  • 更新了答案,请查收。有一点拼写错误:)
  • 再次更新原帖。我对错误感到困惑,因为它似乎正在传递 ID。
  • 有没有calendar_id的记录吗?您能否确认该关联是否有效?
  • 所以这意味着..有些值..没有calendar_id,您可以进行验证,它应该可以工作
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多