views:

86

answers:

3

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?

+4  A: 

assuming:

post = Post.find(params[:id])

and post model contains:

has_many :comments

then you can:

comments = post.comments
first_comment = comments.first
Question Mark
That's a lot of unnecessary variable assignment for such a simple task.
Wahnfrieden
Just to illustrate the process
Question Mark
Awesome perfect!
Elliot
+2  A: 
Post.find(123).comments.first

Where 123 is your post ID.

Wahnfrieden
urgh that looks gross
Question Mark
why?
Wahnfrieden
find is by default by id, and find(:first) (before your edit) compared to .first is nasty
Question Mark
Thanks, cleaned up.
Wahnfrieden
+1  A: 

@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')
frankodwyer