0

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.rbcomments_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.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にresources:commentsからsが欠落していることに気付きました。修正バージョン:

  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 に答える