RoR - 通过关联创建的外键并迁移或“手动”创建(或脚手架)?

发布于 2024-11-01 05:01:24 字数 632 浏览 6 评论 0原文

刚刚开始学习 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

祁梦 2024-11-08 05:01:24

你是对的。您需要在创建脚手架/模型/迁移时指定外键,如您所说,以使数据库正确,并且 has_many 会为您处理模型。

因此,对于支架(或模型)的初始生成,只需执行:

rails generate scaffold post body:text title:string user_id:integer

如您所述,并为模型本身添加 has_many

对于稍后的添加,您将构建一个新的迁移,例如(假设您想使用生成,但您可以编写自己的迁移):

rails generate migration add_user_id_to_posts user_id:integer

这样,您可以运行 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:

rails generate scaffold post body:text title:string user_id:integer

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):

rails generate migration add_user_id_to_posts user_id:integer

With that, you can run a rake db:migrate, and then update your model with a has_many or whatever association you need.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文