2014-01-05 147 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