【问题标题】:rails routing show action nested resourcesrails routing 显示操作嵌套资源
【发布时间】:2012-09-29 19:49:11
【问题描述】:

是的,问题是,我创建了一个这样的嵌套资源:

resources :albums do 
  resources :elements
end

然后 rake routes 命令显示:

album_element GET /albums/:album_id/elements/:id(.:format) elements#show

所以当我在 .../专辑/1 我可以前往 .../专辑/1/元素

这会启动元素控制器的索引操作,就好了。 但是如果我将 index.html.erb 编辑为

<%= link_to 'Show', album_element_path %>

我收到这样的错误:

Started GET "/albums/1/elements" for 176.221.47.67 at Tue Oct 09 14:25:39 +0200 2012
Processing by ElementsController#index as HTML
Parameters: {"album_id"=>"1"}
Rendered elements/index.html.erb within layouts/application (9.2ms)
Completed 500 Internal Server Error in 123ms

ActionController::RoutingError (No route matches {:controller=>"elements", :action=>"show"}):
app/views/elements/index.html.erb:29:in `_app_views_elements_index_html_erb___13604879__168097178'
app/views/elements/index.html.erb:18:in `each'
app/views/elements/index.html.erb:18:in `_app_views_elements_index_html_erb___13604879__168097178'
app/controllers/elements_controller.rb:7:in `index'

所以它说没有路线匹配......但我实际上在我的 rake 路线中显示了它? 我做错了什么?

【问题讨论】:

    标签: ruby-on-rails resources controller routes nested


    【解决方案1】:

    您需要为专辑元素路径提供两个必要的参数:

    <%= link_to 'Show', album_element_path(@album, @element) %>
    

    【讨论】:

    • 感谢您的快速回答,但我收到另一个错误。 Probalby 我需要设置@albums 吗?但是哪里 ?我改成 并在元素控制器的show方法中添加:@album= Album.find(params[:album_id])
    • 如果有人对解决方案感兴趣,那就是: 因为我在 for each - 并且不得不使用 element 代替@element.
    • @element 可能需要替换为您在 index.html.erb 中使用的迭代器
    • 嗯现在我添加了 但是当我点击它时,我得到: ActionView::Template::Error (undefined method ` element_path' for #:0xebde59f4>): 1: 我必须以某种方式修复这个@element 吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多