Show the first record in rails

Assuming I have a comment model and a post model,

What code can be used in a view to display the first comment of a linked post?

+2


source to share


3 answers


given that:

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

      

and the post-model contains:



has_many :comments

      

then you can:

comments = post.comments
first_comment = comments.first

      

+4


source


Post.find(123).comments.first

      



Where 123 is your post ID.

+3


source


@ 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







All Articles