链接到文章控制器'show'动作的嵌套评论'show'动作

时间:2014-04-23 18:37:32

标签: ruby-on-rails

我正在尝试链接到' show'来自' show'的嵌套评论的动作其父文章控制者的行动。

resources :articles do
  resources :comments
end

我知道链接应该如下所示:

<%= link_to "View Comment", article_comment_path(@article, @comment) %>

@ articles在ArticlesController中定义为:

def show
  @article = Article.find(params[:id])
  @comment = ???
end

我很困惑如何定义@comment以获得正确的评论:id为链接工作。

@comment也属于current_user。

1 个答案:

答案 0 :(得分:2)

假设某篇文章有多个评论,您将需要检索该集合并在其上循环。

def show
  @article = Article.find(params[:id])
  @comments = @article.comments
end

然后在视图中:

<% @comments.each do |comment| %>
  <%= link_to "View Comment", article_comment_path(@article, comment) %>
<% end %>

更好的是,您可以在视图中执行此操作:

<% @article.comments.each do |comment| %>
  <%= link_to "View Comment", article_comment_path(@article, comment) %>
<% end %>

然后您无需在控制器中定义@comments

相关问题