https://github.com/railscasts/154-polymorphic-association/tree/master/revised/blog-afterで ryanb が説明した方法でコメント システムを試しています。
これは、 routes.rbに見られる Rails 3 のネストされたリソース ルーティングを使用します。
resources :articles do
resource :comments
end
コメントは、 articles_controller.rbとcomments_controller.rbに見られるように、親の型と ID によって読み込まれます。
class ArticlesController < ApplicationController
...
def show
@article = Article.find(params[:id])
@commentable = @article
@comments = @commentable.comments
@comment = Comment.new
end
class CommentsController < ApplicationController
before_filter :load_commentable
def index
@comments = @commentable.comments
end
...
private
def load_commentable
resource, id = request.path.split('/')[1, 2]
@commentable = resource.singularize.classify.constantize.find(id)
end
...
end
コメントのビュー テンプレートにコメントの編集または破棄アクションへのリンクを追加するにはどうすればよいですか?
<% @comments.each do |comment| %>
<div class="comment">
<%= simple_format comment.content %>
<%= link_to "Delete", comment, method: :delete %>
</div>
<% end %>