Ruby-on-rails Rails 生成 has_many 关联

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20368972/
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 23:06:05  来源:igfitidea点击:

Rails generate has_many association

ruby-on-railsrubyruby-on-rails-4

提问by Passionate Engineer

Is there a way to generate has_many association for a column using Rails generate scaffoldcommand in the console?

有没有办法Rails generate scaffold在控制台中使用命令为列生成 has_many 关联?

I know belongs_tois available and there are use cases of referencesbut not sure of has_many

我知道belongs_to可用,并且有使用案例references但不确定has_many

回答by Alex Peachey

There is no column for a has_manyrelationship. A belongs_tois backed by a column which holds a foreign key.

has_many有关系列。Abelongs_to由包含外键的列支持。

So if you generate a scaffold: rails g scaffold Post

所以如果你生成一个脚手架: rails g scaffold Post

And then you generate another scaffold: rails g scaffold Comment post:references

然后你生成另一个脚手架: rails g scaffold Comment post:references

Then rails will create a migration that adds a column named post_idto the Comment table and creates an index on it. For both tables, it creates foreign key constraints between comments(post_id)and posts(id). Rails will also add belongs_to :postin the Comment model.

然后 rails 将创建一个迁移,将一个名为post_idComment 表的列添加到该列并在其上创建一个索引。对于这两个表,它在comments(post_id)和之间创建外键约束posts(id)。Rails 还将添加belongs_to :post到 Comment 模型中。

At anytime you can add a has_manyto a model as long as another model belongs_tothe first model and has a migration with the foreign key column.

您可以随时has_many向模型添加一个,只要另一个模型belongs_to是第一个模型并且具有外键列的迁移。