Reputation: 553
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.
Upvotes: 0
Views: 62
Reputation: 239311
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
Upvotes: 2