Asso
Asso

Reputation: 47

Rails controller

Newb in Rails

i Have this problem that i cannot figure out. I've followed the sample blog dimostration form the ruby doc but now i have a problem.

Let's say that in the app index page for each post i also want to show the first comment of that post.

sure i need to cycle all the post to get the post id but how can i get the first comment of that post?

how can i manage the homeController and the view ?

thanks since now!

Upvotes: 0

Views: 157

Answers (2)

Chris Drappier
Chris Drappier

Reputation: 5370

a better approach would be: @post.comments.first.

and eager load your comments when you find your posts: @posts = Post.all(:include => :comments)

This way, you only run one query per request. In the previous answer you run an additional select statement for every post on the index page.

Upvotes: 1

scottru
scottru

Reputation: 5370

It's a bit hard to follow the question you're asking and the detailed syntax might vary, but you're going to want something like

first_comment = Comment.find_by_post_id(@post.id, :order => "created_at ASC")

(find_by_x defaults to the first of x based on your ordering, so this will only return one element.

I hope that helps.

Upvotes: 2

Related Questions