Ruby on rails 如何在RoR中获取所选帖子的评论列表?

Ruby on rails 如何在RoR中获取所选帖子的评论列表?,ruby-on-rails,model-view-controller,Ruby On Rails,Model View Controller,我创建了示例rails应用程序,其中的应用程序列表显示在DataTable中。如果我选择了其中一行,我希望文章的视图显示一个表,下面是该文章的注释列表。在post controller中,我有: # GET /posts # GET /posts.json def index @posts = Post.all end # GET /posts/1 # GET /posts/1.json def show @post = Post.find(param

我创建了示例rails应用程序,其中的应用程序列表显示在DataTable中。如果我选择了其中一行,我希望文章的视图显示一个表,下面是该文章的注释列表。在post controller中,我有:

  # 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页面上创建列表的帖子的索引返回一样。我使用什么参数来收集找到的帖子的评论(如果存在)?comments架构有一个名为“post_id”的列

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

def show
  @post = Post.find(params[:id])
  @comments = Comment.where(post_id: @post.id)
end
或者,如果在
Post
模型中定义了
comments
关联,则更好

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

非常感谢。很难找到RoR许多部分的明确答案。感谢您的帮助。如果您不知道,请尝试本教程