繁体   English   中英

获取所有评论

[英]Getting all comments

我有两种模式:帖子和评论。 每个评论都属于一个帖子。 我想要一个页面,其中包含所有评论,而不仅仅是帖子的评论。 我似乎无法使这看似简单的事情起作用。

这是我的控制器:

def top
  @topcomments = @comments.order("created_at desc")
end 

我收到“未定义的方法顺序”错误。

如果要直接访问注释,而不是通过与其他模型的关系访问,则需要访问模型本身Comment

def top
  @topcomments = Comment.order('created_at desc')
end 

您如何获得每个评论的帖子

假设您在评论和帖子之间建立了正确的关系,则只需为每个评论访问.post 您可以使用includes(:post)来避免n + 1问题

def top
  @topcomments = Comment.order('created_at desc').includes(:post)

  @topcomments.each |comment|
    comment.post # here is the post
  end
end
def top
    @topcomments = Comment.order("created_at desc")
end 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM