开发者

Nested Model/Routes in Rails 3

I have a simple blogging functionality in my Rails 3 app. I am trying to add commenting to each post. The BlogComment model has a property, blog_post_id, to be able to find the corresponding comments for each post. I already setup my associations in the model, I also nested BlogComments under BlogPost in the routes file.

However, I can't figure out how to give each BlogPost access to i开发者_StackOverflow社区ts respective comments through the controller so that they can be shown later in the view.


Assuming you've setup BlogPost with has_many :blog_comments, and BlogComment with belongs_to :blog_post, you can access the post's comments in the post controller with:

@blog_post = BlogPost.find(params[:id])
@blog_post_comments = @blog_post.blog_comments


It would be best to have this as a comments association so that you're not re-typing the word blog all the time:

has_many :comments, :class_name => "BlogComment"

This would still let you have your model called BlogPost and BlogComment, but when you go to get the comments for a BlogPost object:

@blog_post.comments

No more repetition.


Assumming in your model

BlogPost has many blog_Comments,

In your controller:

@b = BlogPost.find(1)

in your view

@b.blog_Comments.each ....
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜