has_many 关系在商业感知上似乎不正确或不合逻辑,需要像belongs_to_many 这样的东西吗?
我的情况是这样的。 公司有很多用户,用户可能属于很多公司。 当前的实现如下所示。
class Company
has_many :employments
has_many :users, :through => :employments
end
class Employment
belongs_to :company
belongs_to :user
end
class User
has_many :employments
has_many :companies, :through => :employments #This doesn't looks correct
end
它有效,但“用户拥有许多公司”在逻辑上看起来没有意义。它一定是类似于“属于许多公司”之类的东西。 我需要使用 has_and_belongs_to_many 吗?
有人可以建议表示这些关系的正确方法吗?
My situation is like this.
Company has many users and users may belongs to many companies.
And current implementation is something like below.
class Company
has_many :employments
has_many :users, :through => :employments
end
class Employment
belongs_to :company
belongs_to :user
end
class User
has_many :employments
has_many :companies, :through => :employments #This doesn't looks correct
end
It works, but "user has many companies" doesn't looks logically meaningful. It must be some thing like belongs_to_many companies.
Do I need to use has_and_belongs_to_many?
Can some one please suggest the right way for representing these relationships?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您不打算向
Employment
类添加一些特殊行为,并且您实际上并不需要它,那么您应该更好地使用has_and_belongs_to_many
。这样,它仍然会有一些名为CompanyUser
的表,但代码中不会有任何这样的类。添加:
2个对象之间只有3种可能的连接:1对1、1对多和多对多。 Rails 使用
has_*
或belongs_to
指示这 2 个对象中的哪一个将获得外键。所以:一对一:
使用了has_one和belongs_to。具有belongs_to的对象获得FK。
一对多:
使用了has_many和belongs_to。具有belongs_to的对象获得FK。
多对多:
has_many[through] 或 has_and_belongs_to_many 在两个对象中都使用。没有人获得 FK,而是使用 ConnectionTable。
所以不存在“belongs_to_many”这样的东西,因为它与“has_many”相同——提供相同的一对多关系。
If you are not going to add some special behaviour to
Employment
class and you don't really need it, then you should propably better usehas_and_belongs_to_many
. This way it will still have some table calledCompanyUser
, but there will not be any such class in the code.Added:
There are just 3 possbile conections between 2 objects: 1-to-1, 1-to-many and many-to-many. Rails indicates with
has_*
orbelongs_to
what of the 2 objects will get a foreign key. So:1-to-1:
has_one and belongs_to are used. The object with belongs_to gets the FK.
1-to-many:
has_many and belongs_to are used. The object with belongs_to gets the FK.
many-to-many:
has_many[through] or has_and_belongs_to_many are used in both objects. No-one gets a FK, instead a ConnectionTable is used.
So there is no such thing as belongs_to_many, because it would be the same as has_many - providing the same relation 1-to-many.