大家好,我是 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 :post
添加到 Comment 类。但是,当我尝试调用 post.comments
时,出现运行时错误,提示 SQLException: no such column: comments.post_id
。我应该创建一个迁移并在 Comment 下添加 post_id 还是在搭建脚手架时有办法实现这一点?
最佳答案
脚手架实际上提供了一种生成关系的方法,你应该使用:references
数据类型
rails g scaffold Comment body:string author:string post:references
这将为带有 post_id 字段和索引的评论表生成一个迁移。生成器还会将 belongs_to :post
添加到 Comment 模型。
但是它不会生成关系的反面,所以你需要添加
has_many :comments
自己给 Post 模型。如果这是您需要的,您还需要添加嵌套资源路由,因为生成器无法处理。
关于ruby-on-rails - 在搭建脚手架时创建关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13445367/