Show the first record in rails
3 answers
@ post.comments.first will usually work. (@post must be configured in your controller method)
However, it is good to understand that "first" means first in an association, which is usually ordered by id. Since identifiers are auto-incrementing, this is the same as "first added" or "earliest comment". But this is optional.
If your association for comments indicated a different order, then use that first, for example. if your association looked like this:
has_many :comments, :order=>'rating desc'
Then (assuming the "rating" field is somehow set to some value representing the average rating) post.comments.first will give you the highest rating for the comment, not the first one to be added.
In this case, if your comment model has timestamps, you would need to do something like
@post.comments.find(:first, :order=>'created_at asc')
+1
source to share