首页 > 解决方案 > 如何获取 RoR 中选定帖子的评论列表?

问题描述

我已经创建了示例 Rails 应用程序,其中包含在 DataTable 中显示的应用程序列表。如果我选择其中一行,我希望帖子的视图随后显示一个表格,其中包含该帖子的评论列表。在后控制器中,我有:

  # GET /posts
  # GET /posts.json
  def index
    @posts = Post.all
  end
  # GET /posts/1
  # GET /posts/1.json
  def show
    @post = Post.find(params[:id])
    @comments = Comment.find(params[:id])
  end

上面的结果给出了一个错误,它找不到 id = 1 的评论。

我想要做的是最终得到一个列表,就像索引返回的帖子一样,我可以在 post.html.erb 页面上使用它来创建列表。我用什么论据来收集找到的帖子的评论(如果它们存在的话)?评论模式有一个名为“post_id”的列。

标签: ruby-on-railsmodel-view-controller

解决方案


您正在使用您在操作中收到的相同 ID 来检索帖子及其评论。这是错误的,那只是帖子ID。您可以像这样使用您的帖子检索它们

def show
  @post = Post.find(params[:id])
  @comments = Comment.where(post_id: @post.id)
end

或者,更好的是,如果您在模型comments中定义了关联Post

def show
  @post = Post.find(params[:id])
  @comments = @post.comments
end

推荐阅读