使用 user_id:integer 和 user:references 在 Rails 中生成模型 [英] Generate model in Rails using user_id:integer vs user:references
问题描述
我对如何生成属于另一个模型的模型感到困惑.我的书使用这种语法将 Micropost 与用户关联起来:
I'm confused on how to generate a model that belongs_to another model. My book uses this syntax to associate Micropost with User:
rails generate model Micropost user_id:integer
但是http://guides.rubyonrails.org/ 说要这样做:
rails generate model Micropost user:references
这两个产生的迁移是不同的.另外,对于前者,rails 如何知道 user_id
是引用 user
的外键?谢谢!
The migrations generated by these 2 are different. Also, for the former, how does rails know that user_id
is a foreign key referencing user
? Thanks!
推荐答案
当您运行迁移时,两者都会生成相同的列.在 rails 控制台中,可以看到是这样的:
Both will generate the same columns when you run the migration. In rails console, you can see that this is the case:
:001 > Micropost
=> Micropost(id: integer, user_id: integer, created_at: datetime, updated_at: datetime)
第二个命令在您的 Micropost 模型中添加了 belongs_to :user
关系,而第一个没有.指定此关系后,ActiveRecord 将假定外键保存在 user_id
列中,并将使用名为 User
的模型来实例化特定用户.
The second command adds a belongs_to :user
relationship in your Micropost model whereas the first does not. When this relationship is specified, ActiveRecord will assume that the foreign key is kept in the user_id
column and it will use a model named User
to instantiate the specific user.
第二个命令还在新的 user_id
列上添加索引.
The second command also adds an index on the new user_id
column.
这篇关于使用 user_id:integer 和 user:references 在 Rails 中生成模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!