URLヘルパーは、実際にオブジェクトを受け入れて、関連付けのルートを作成します。つまり、アイテム内にコメント用のネストされたルートがあると仮定すると、
resources :items do
resources :comments
end
あなたはすることができlink_to
ますnew_item_comments_path(item)
。
このメソッドは、HTMLタグを作成するためにフィードするルートにnew_item_comments_path(item)
基づいて文字列URLを作成します。new_item_comments
link_to
<a>
より明確にするために、あなたの見解では次のようになります。
<%= link_to 'View', item %>
<%= link_to 'Edit', edit_item_path(item) %>
<%= link_to 'Delete', item, method: :delete, data: { confirm: 'Are you sure?' } %>
<%= link_to 'Add Comment', new_item_comments_path(item) #-> (instead of ???) %>
この場合、item
渡すのは現在のアイテムへの参照です。これにより、URLヘルパーはルートからそのアイテムのURLを作成できます。
ルーティングのRailsガイドは、参考になるはずです。
これは、コメントコントローラが適切な場所に適切なものを割り当てることを前提としています。あなたはそれを理解しているように見えましたが、明確にするために(そして将来の訪問者のために)説明します
class CommentsController < ApplicationController
# GET /item/:item_id/comments/new
def new
@comment = Comment.new
@item = Item.find(params[:item_id])
@comment.item = @item
# render
end
# POST /item/:item_id/comments
def create
@comment = Comment.new(params[:comment])
@item = Item.find(params[:item_id])
@comment.item = @item
# if @comment.save blah
end
end