Rails模型关系及迁移
我在尝试构建具有多个模型以及它们之间的关系的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
关联声明仅适用于 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.