2015-05-11 38 views
0

在下面的代碼段編輯在軌

.comment 
    %p= comment.comment 
    %p= comment.user.email 

    = link_to 'Edit', edit_post_comment_path(comment.post, comment) 
    = link_to "Delete", [comment.post, comment], method: :delete, data: {confirm: 'Are you sure"'} 

一個嵌套的資源,爲什麼都編輯刪除拿在comment.post作爲參數?這是什麼意思?

回答

2

它需要comment.post,因爲你已經嵌套路由,請檢查您擁有如下定義路由,您的routes.rb文件:

resources :posts do 
    resources :comments 
end 

和你的路由是編輯和刪除是

edit_post_comment GET /posts/:post_id/comments/:id/edit(.:format) comments#edit  

DELETE /posts/:post_id/comments/:id(.:format) comments#destroy 

這就是爲什麼你總是需要通過comment.post作爲參數。

如果你不想comment.post作爲參數,你可以改變你的路線爲:

resources :posts 
resources :comments 

或者如果你不知道,不想在任何特定的行動來傳遞comment.id做你的路由作爲

resources :posts do 
    resources :comments, :except => [:delete] 
end 

resources :comments, :only => [:delete] 

注:我假設你不想爲comment.post參數:刪除操作

+0

感謝詳細的解釋!對不起,沒有澄清這個問題,但我試圖找出它爲什麼是comment.post而不是post.comment。由於評論嵌入帖子內,我認爲它是post.comment,並且無法弄清楚爲什麼它錯了,直到後來大量使用Google。是有原因的,還是僅僅是約定? – user3277633

+0

如果你檢查路線(即嵌套的路線),你需要同時發表評論和發佈,所以你必須通過'comment.post',因爲你沒有你的視圖的後期對象。 –

+0

啊我明白了!謝謝!! – user3277633

0

評論是一個嵌套的資源,這意味着評論屬於一個職位。因爲軌道路線定義在RESTFUL方式。

如果您以RESTful方式查看,評論資源中的所有CRUD操作都需要發佈資源ID,因爲評論與帖子相關聯。

不僅'編輯'和'刪除'操作需要父資源ID,所有的CRUD操作都需要它。

看一看嵌套資源部分的here