我正在以 ryanb 在https://github.com/railscasts/154-polymorphic-association/tree/master/revised/blog-after中描述的方式尝试评论系统。
它使用在routes.rb中看到的 Rails 3 嵌套资源路由:
resources :articles do
resource :comments
end
评论由父母类型和 id 加载,如articles_controller.rb和comments_controller.rb所示:
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 %>