2013-04-29 61 views
11

我是一個完全新手在Rails中。如何使用Link_to與嵌套資源

我已經創建了一個Web應用程序,我可以通過/posts/123/comments//posts/123/comments/new訪問,但我不知道如何使用的link_to在索引視圖來顯示具體的評論,當我嘗試連接它,會出現「無路由「或」未定義符號「。

我在模型中定義的帖子和評論之間有嵌套的have_many關係,並且在我執行rake路由時出現routes.rbpost_comments GET /posts/:post_id/sensors(.:format)comments#index

我該怎麼做?

回答

7

嘗試所有它沒有完全工作的答案後,我找到了一種方法來解決它。 在第一關鍵時刻,我用

post_comments_url(@帖子,評論)

,其中註釋是@ post.each內的項目。

它生成一個「奇怪的」路線,使用。而不是/像 「後/ 34/comments.2」,我固定它用單數形式:

post_comment_url(@帖子,評論)

感謝您的幫助!

+0

你試過'link_to'show',[@post,comment]'? – toch 2013-05-02 07:54:04

12

如果您已經定義嵌套資源(當然,你的模型CommentPost關聯)

resources :posts do 
resources :comments 
end 

您可以鏈接評論如下

<!-- /posts/:post_id/comments/:id --> 
<%= link_to 'Show', [@comment.post, @comment] %> 

我寫了一個full example of nested resources in a past blog post

+0

我已將我的密碼更改爲 <%@ posts.each do | item | %> ​​<%= item。農佈雷%> ​​<%= item.info%> ​​<%=的link_to '顯示',[@ comment.post,@comment]%> <% end %> 和它並不運行...出現未定義的方法帖子。 我該怎麼做? 謝謝! – fuco 2013-04-29 11:59:19

+0

這可能是因爲你的'Comment'模型沒有與'Post'關聯。你應該在'Comment'模型中有'belongs_to:post'。如果沒有,這是正常的,它是未定義的。你也可以用包含註釋的Post對象代替'@ comment.post'(可能是你的案例中的'item')。 – toch 2013-04-29 12:04:49

+0

這對我不起作用:它抱怨'post_comment_path'是未定義的(在'rake routes'中顯示的路由是'post_comments',複數) – digitig 2014-07-14 16:14:06

0

除了toch的答案,你可以在Rails控制檯的幫助下調試你的link_to調用。

對於這一點,你需要加載視圖助手在控制檯:

irb(main):001:0> include ActionView::Helpers::UrlHelper 
=> Object 
irb(main):002:0> helper.link_to "posts", app.posts_path 
=> "<a href=\"/posts\">foo</a>" 

另一個工具,類似於耙路線路線調試:https://github.com/schneems/sextant

1

Get方法名從第一列

rake routes 

並相應地傳遞ID。當然後綴與_path IR _url 方法名要知道更多,請訪問Rails guide