开发者

Rails controller

开发者 https://www.devze.com 2022-12-25 06:37 出处:网络
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.

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 c开发者_Python百科an i manage the homeController and the view ?

thanks since now!


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消