39

嗨,我是 Ruby on Rails 的新手。我正在尝试创建一个小型博客站点。我有两张表帖子和评论。每个帖子都会有很多评论。我使用这些命令生成表。

rails g scaffold Post title:string body:text author:string
rails g scaffold Comment body:string author:string

现在我想将关系添加到模型类。我添加has_many :comments到 Post 类和belongs_to :postComment 类。但是,当我尝试调用时,post.comments我会收到运行时错误消息SQLException: no such column: comments.post_id。我应该创建一个迁移并在 Comment 下添加 post_id 还是有办法在搭建脚手架时实现这一点?

4

3 回答 3

152

Scaffold 实际上提供了一种生成关系的方法,你应该使用:references数据类型

rails g scaffold Comment body:string author:string post:references

这将为带有 post_id 字段和索引的评论表生成迁移。生成器还将添加belongs_to :post到 Comment 模型中。

但是,它不会生成关系的反面,因此您需要添加

has_many :comments

自己到 Post 模型。如果这是您需要的,您还需要添加嵌套资源路由,因为生成器无法处理此问题。

于 2014-10-03T10:07:21.320 回答
9

你绝对是在正确的轨道上。如果您post_id在生成Comment脚手架时添加列,那么您的关系将起作用(尽管您仍然需要添加has_many :commentsand belongs_to :post

所以更新后的生成器调用如下所示:

rails g scaffold Comment body:string author:string post_id:integer
于 2012-11-18T22:44:50.607 回答
2

你也可以belongs_to这样使用:

rails g scaffold Comment body:string author:string post:belongs_to
于 2018-12-19T06:32:59.827 回答