2011-02-28 97 views
0

我在Rails 3应用程序中有一个简单的博客功能。我正在为每篇文章添加评论。 BlogComment模型有一个属性blog_post_id,能够为每个帖子找到相应的评论。我已经在模型中设置了我的关联关系,我还在BlogPost的路由文件中嵌套了BlogComments在Rails 3中嵌套模型/路径3

但是,我不知道如何通过控制器给每个BlogPost访问其各自的注释,以便它们可以在视图中稍后显示。

回答

1

假设你已经安装的博文与has_many :blog_comments,并BlogComment与belongs_to :blog_post,您可以访问这篇文章的评论中柱控制器:

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

创建新评论时,是否必须设置我的评论模型的'blog_post_id'属性? – mbreedlove 2011-03-01 00:56:41

+1

如果您通过后期对象分配或创建对象,将会为您处理这些关联,包括设置外键。例如,@blog_post_comments = @ blog_post.comments.build为您提供了一个带有正确ID设置的新评论对象,并且如果您将评论作为嵌套资源传递给POST对象,那么新评论将使用正确的协会也是如此。在这里看看更多的信息:http://guides.rubyonrails.org/getting_started.html#building-a-multi-model-form – clemensp 2011-03-01 01:26:28

0

Assumming在模型

博客帖子有很多blog_Comments,

在你的控制器:

@b = BlogPost.find(1)

在你看来

@b.blog_Comments.each .... 
1

这将是最好有这个作为comments关联,这样你不重新键入单词blog所有的时间:

has_many :comments, :class_name => "BlogComment" 

这仍然让你有你的模型叫BlogPostBlogComment,但是当你去得到一个BlogPost对象的意见:

@blog_post.comments 

没有更多的重复。