mbreedlove
mbreedlove

Reputation: 336

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 its respective comments through the controller so that they can be shown later in the view.

Upvotes: 0

Views: 303

Answers (3)

Ryan Bigg
Ryan Bigg

Reputation: 107728

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.

Upvotes: 1

macarthy
macarthy

Reputation: 3069

Assumming in your model

BlogPost has many blog_Comments,

In your controller:

@b = BlogPost.find(1)

in your view

@b.blog_Comments.each ....

Upvotes: 0

clemensp
clemensp

Reputation: 2510

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

Upvotes: 1

Related Questions