Assuming I have a comments model and a posts model,
What code can I use in a view to display the first comment of the post being linked?
Assuming I have a comments model and a posts model,
What code can I use in a view to display the first comment of the post being linked?
assuming:
post = Post.find(params[:id])
and post model contains:
has_many :comments
then you can:
comments = post.comments
first_comment = comments.first
@post.comments.first will normally work. (@post should be set up in your controller method)
However it is good to realise that 'first' means first in the association, which is normally ordered by id. Since ids autoincrement, this happens to be the same as 'first added' or 'earliest comment'. But it doesn't have to be.
If your association for comments specified a different ordering, then first will use this, e.g. if your association looked like this:
has_many :comments, :order=>'rating desc'
Then (assuming the 'rating' field is set up somehow to be some value that represents the average rating) post.comments.first would give you the highest rated comment, not the first to be added.
In that case, assuming your comments model has timestamps, then you'd need to do something like
@post.comments.find(:first, :order=>'created_at asc')