RoR - 通过关联创建的外键并迁移或“手动”创建(或脚手架)?
刚刚开始学习 Ruby on Rails。我正在使用 RoR 3。我已阅读以下内容: http://guides.rubyonrails.org/association_basics.html
但我想确保我完全理解。
创建新模型时(我现在通过脚手架进行),我应该在此时指定foreign_key字段,还是关联可以完全处理该字段?我相信关联仅在应用程序级别,而不是在数据库级别,对吗?
所以我认为我必须这样做:
rails generate scaffold post body:text title:string user_id:integer
所以总而言之,在创建博客应用程序时,我必须在帖子模型中指定 user_id 字段,还是用户模型的 has_many :posts
负责实际将其添加到我迁移时的数据库(我的是mysql)?
如果答案是我应该在首先创建模型时(通过脚手架或手动)执行这些操作,那么当我稍后决定要添加外键时会发生什么,我是否必须将其添加为 <在新迁移中执行 code>execute 语句?
Just starting to learn Ruby on Rails. I'm using RoR 3. I have read this: http://guides.rubyonrails.org/association_basics.html
But I want to make sure I understand completely.
When creating a new model (I'm doing via scaffold for now), should I specify foreign_key fields at that point, or does the association handle that completely? I believe that association is only at app level, not at the db level, correct?
So I think I must do:
rails generate scaffold post body:text title:string user_id:integer
So in summary, when creating a blog application, must I specify the user_id field in the post model, or does the user model's has_many :posts
take care of actually adding that to the db (mine is mysql) when I migrate?
And if the answer is that I should do them when I create the model in the first place (via scaffold or by hand), what happens when I decide later on that I want to add a foreign key, must I add that as an execute
statement in a new migration?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你是对的。您需要在创建脚手架/模型/迁移时指定外键,如您所说,以使数据库正确,并且 has_many 会为您处理模型。
因此,对于支架(或模型)的初始生成,只需执行:
如您所述,并为模型本身添加
has_many
。对于稍后的添加,您将构建一个新的迁移,例如(假设您想使用生成,但您可以编写自己的迁移):
这样,您可以运行
rake db:migrate
,然后使用has_many
或您需要的任何关联更新您的模型。You're correct. You need to specify the foreign key when you create your scaffold/model/migration as you stated to get the DB to be correct, and the has_many takes cares of the model for you.
So for initial generation of a scaffold (or model), just do:
as you stated, and add the
has_many
for the model itself.For additions later on, you would make up a new migration, something like (assuming you want to use generation, but you could write your own migration):
With that, you can run a
rake db:migrate
, and then update your model with ahas_many
or whatever association you need.