我正在以https://github.com/railscasts/154-polymorphic-association/tree/master/revised/blog-after中的ryanb描述的方式尝试评论系统。
它使用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 %>
答案 0 :(得分:1)
将资源作为数组传递:
<%= link_to "Delete", [@article, @comment], method: :delete %>
答案 1 :(得分:0)
使用jdoes建议我更多地关注数组传递并注意到routes.rb缺少资源中的s:comments。修正版:
resources :articles do
resources :comments do
end
end
现在,模板只需将链接作为数组即可完美运行。
<% @comments.each do |comment| %>
<div class="comment">
<%= simple_format comment.content %>
<%= link_to "Delete", [@commentable, comment], method: :delete %>
</div>
<% end %>