Rails模型关系及迁移

发布于 2024-10-22 00:58:17 字数 577 浏览 2 评论 0原文

我在尝试构建具有多个模型以及它们之间的关系的 Rails 应用程序时遇到一些问题...

如果我采用一个基本示例,例如模型组、模型用户和模型汽车,

class Group < ActiveRecord::Base
   has_many :users
end 
class User < ActiveRecord::Base
  belongs_to :group
  has_many :cars
end 
class Car < ActiveRecord::Base
  belongs_to :user
end

这些关系语句会自动创建以下内容功能:

  • group.users
  • user.group
  • user.cars
  • car.user

似乎我们有时需要在迁移中创建“引用”(例如在 Car 表中添加对 User 的引用),但这总是需要的吗? 在这种情况下,创建迁移和在模型中添加关系语句有什么区别?我有时感觉这也是出于同样的目的。

非常感谢您的帮助,

问候,

Luc

I have some problem trying to understand when building a rails app with several models and relation ships between them...

If I take a basic example like a model Group, a model User and a model Car

class Group < ActiveRecord::Base
   has_many :users
end 
class User < ActiveRecord::Base
  belongs_to :group
  has_many :cars
end 
class Car < ActiveRecord::Base
  belongs_to :user
end

Will those relation ship statements automatically create the following functions:

  • group.users
  • user.group
  • user.cars
  • car.user

It seems that we sometimes need to have to create "references" in migration (like adding a reference toward User in Car table) but is this always required ?
In this case, what is the difference of creating the migration and of adding the relationship statement in the models ? I sometimes have the feeling this is used for the same purpose.

Thanks a lot for your help,

Regards,

Luc

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(1

策马西风 2024-10-29 00:58:17

关联声明仅适用于 Rails。您必须在数据库中定义外键(引用),以便Rails 可以正确保存数据。

请记住,尽管有所有魔力,它仍然由关系数据库支持,因此从长远来看,良好的实践将会得到回报。

The association declarations are there for Rails only. You have to define the foreign keys (references) in the database, so that Rails can properly save the data.

Remember, despite all the magic, it's still backed by a relational database, so good practices there will pay off in the long run.

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