0

I have two models: posts and comments. Each comment belongs to a post. I would like to have a page of all comments not just the comments for a post. I can't seem to get this seemingly simple thing to work.

Here is my controller:

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

I am getting an 'undefined method order' error.

Sergio Tulentsev
  • 226,338
  • 43
  • 373
  • 367
user2759575
  • 553
  • 3
  • 25

2 Answers2

2

If you want to access comments directly, and not through a relationship with another model, you need to access the model itself, Comment:

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

how would you get the post for each comment

Assuming you have a relationship set up correctly between comments and posts, you would just access .post for each comment. You can use includes(:post) to avoid the n+1 problem.

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

  @topcomments.each |comment|
    comment.post # here is the post
  end
end
Community
  • 1
  • 1
user229044
  • 232,980
  • 40
  • 330
  • 338
  • Awesome that worked. Quick question: how would you get the post for each comment. For each comment i am doing a 'link_to (@post.title)' but it is an undefined post. – user2759575 Jan 05 '14 at 10:13
  • @user2759575 See update; too much to fit in a comment. – user229044 Jan 05 '14 at 19:08
  • OK so comment.post gets the post but then comment.post.title gets 'undefined method title'. It looks like this: @topcomments.each do |comment] link_to (comment.post.title) end – user2759575 Jan 05 '14 at 19:17
1
def top
    @topcomments = Comment.order("created_at desc")
end 
arun15thmay
  • 1,062
  • 1
  • 9
  • 19