Rails 生成 has_many 关联 [英] Rails generate has_many association
问题描述
有没有办法在控制台中使用 Rails generate scaffold
命令为列生成 has_many 关联?
Is there a way to generate has_many association for a column using Rails generate scaffold
command in the console?
我知道 belongs_to
可用,并且有 references
的用例,但不确定 has_many
I know belongs_to
is available and there are use cases of references
but not sure of has_many
推荐答案
has_many
关系没有列.belongs_to
由包含外键的列支持.
There is no column for a has_many
relationship. A belongs_to
is backed by a column which holds a foreign key.
所以如果你生成一个脚手架:rails g scaffold Post
So if you generate a scaffold: rails g scaffold Post
然后你生成另一个脚手架:rails g scaffold Comment post:references
And then you generate another scaffold: rails g scaffold Comment post:references
然后 rails 将创建一个迁移,将名为 post_id
的列添加到 Comment 表并在其上创建索引.对于这两个表,它在 comments(post_id)
和 posts(id)
之间创建外键约束.Rails 还将在 Comment 模型中添加 belongs_to :post
.
Then rails will create a migration that adds a column named post_id
to 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 :post
in the Comment model.
您可以随时向模型添加 has_many
,只要另一个模型 belongs_to
第一个模型并且具有外键列的迁移.
At anytime you can add a has_many
to a model as long as another model belongs_to
the first model and has a migration with the foreign key column.
这篇关于Rails 生成 has_many 关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!