Ruby-on-rails 搭建脚手架时建立关系

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13445367/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 21:02:44  来源:igfitidea点击:

Create relationships when scaffolding

ruby-on-railsrubyscaffolding

提问by Stefan Bossbaly

Hi I am new to Ruby on Rails. I am trying to create a small blog site. I have two tables Posts and Comments. Each Post will have many comments. I generate the tables using these commands.

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

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

Now I want to add the relationship to the model classes. I add has_many :commentsto the Post class and belongs_to :postto the Comment class. However when I try to call post.commentsI get a runtime error saying SQLException: no such column: comments.post_id. Should I create a migration and add post_id under Comment or is there a way to achieve this when scaffolding?

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

回答by JamieD

Scaffold actually provides a way to generate relationships, you should use the :referencesdata type

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

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

This will generate a migration for the comments table with a post_id field and index for it. The generator will also add belongs_to :postto the Comment model.

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

It will not however generate the reverse side of the relationship so you'll need to add

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

has_many :comments

to the Post model yourself. You will also need to add nested resource routing if this is something you need as the generator can not handle this.

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

回答by agmin

You are definitely on the right track. If you add the post_idcolumn when generating the Commentscaffold your relationship will then work (although you still need to add the has_many :commentsand belongs_to :post)

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

So the updated generator call would look like this:

所以更新后的生成器调用看起来像这样:

rails g scaffold Comment body:string author:string post_id:integer

回答by Jeremy Lynch

You can also use belongs_tolike this:

你也可以belongs_to这样使用:

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