簡體   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