【问题标题】:link to nested comment 'edit' action from parent articles controller 'index从父文章控制器“索引”链接到嵌套评论“编辑”操作
【发布时间】: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


【解决方案1】:

我不知道它在控制器中是如何工作的。但我认为无论如何最好将方法移动到帮助器中并从那里调用它。在帮助器中定义的方法自动可用于您的视图

你可以这样做:

def comment(article)
    @comment = current_user.comments.where(article_id: article.id)
end

那么您的视图将如下所示:

<% @articles.each do |article| do %>
   <% comment(article) %>
   ....more code....

就像你说的,如果你在控制器中移动它,where(article_id: article.id) 会绊倒你,因为你不知道id 绑定到哪个article

编辑:

如果你真的想访问控制器内部的方法,你可以按照this post的建议:

class ArticlesController < ActionController::Base
  def comment(article)
      @comment = current_user.comments.where(article_id: article.id)
  end
   helper_method :comment(article)
end

但是,当您可以在 helper 中轻松完成此操作时,为什么还要遇到麻烦。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-09-17
    • 2014-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    相关资源
    最近更新 更多