【发布时间】:2014-05-14 23:45:14
【问题描述】:
我正在尝试从其父文章控制器的“索引”操作链接到嵌套评论的“编辑”操作。如果不存在评论,则链接将转到“新”操作。
resources :articles do
resources :comments
end
问题似乎是如何在 Articles 控制器中定义 @comment 以获得具有相关文章 ID 的正确评论 ID。
文章控制器包含:
def index
@articles = Article.all
end
我可以通过在视图'index.html.erb'中定义@comment来完成我想要的(见下文):
<% @articles.each do |article| do %>
<% @comment = current_user.comments.where(article_id: article.id) %>
<% if @comment.empty? %>
<%= link_to "New Comment", new_article_comment_path(article) %>
<% else %>
<% @comment.each do |comment| %>
<%= link_to "Edit Comment", edit_article_comment_path(article, comment) %>
<% end %>
<% end %>
<% end %>
但我更愿意在 Articles 控制器中定义 @comment。我不确定如何在没有 id 的情况下在 Articles 控制器中实现“@comment = current_user.cmets.where(article_id:article.id)”,因为它是“索引”操作。
一定是我缺少的一些简单的东西。
【问题讨论】:
-
您不想将其移动到
helper中吗?您想在articles_controller内移动。那就是以@comment开头的那一行,一直向下 -
我只想将“@comment”定义从视图移动到文章控制器。
标签: ruby-on-rails