0

我正在以 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.rbcomments_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.html.erb:

<% @comments.each do |comment| %>
  <div class="comment">
    <%= simple_format comment.content %>
    <%= link_to "Delete", comment, method: :delete %>
  </div>
<% end %>
4

2 回答 2

1

将资源作为数组传递:

<%= link_to "Delete", [@article, @comment], method: :delete %>
于 2012-11-25T17:50:20.807 回答
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 %>
于 2012-11-25T20:00:16.393 回答