2014-01-05 63 views
0

我有两种模式:帖子和评论。每条评论都属于帖子。我想有一个所有评论的页面,而不仅仅是一篇文章的评论。我似乎无法得到这个看起来很简单的工作。获取所有评论

这里是我的控制器:

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

我得到一个 '未定义的方法秩序' 的错误。

+0

什么是'@ comments'? –

+0

这就是我所拥有的。不知道该怎么做@comments。 – user2759575

回答

2

如果你想直接访问的意见,而不是通过与其他模型的关系,你需要访问模型本身,Comment

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

你会怎么得到这个职位的每个评论

假设你有一个关系设置正确的文章和评论之间,你只需访问.post为EA ch评论。您可以使用includes(:post)来避免n+1 problem

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

    @topcomments.each |comment| 
    comment.post # here is the post 
    end 
end 
+0

真棒,工作。快速提问:您如何获得每条评论的帖子。对于每条评论,我正在做一个'link_to(@ post.title)',但它是一个未定义的文章。 – user2759575

+0

@ user2759575查看更新;太适合评论。 – meagar

+0

好,所以comment.post获取帖子,但然后comment.post.title获取'未定义的方法标题'。它看起来像这样:@ topcomments.each do | comment] link_to(comment.post.title)end – user2759575

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