特定的一个对多关系 [英] Particular one-to-many relation
问题描述
我有一个Rails 3.1的应用程序有一个用户
模式与众议院
模式(这就像一个组)。我已经设置了许多一对多的关系与加盟者两者之间的模式成员
有一些方法来管理用户的角色,在一些家庭中的连接模型。
I've got a Rails 3.1 app with a User
model and a House
model (this is like a group). I've set up a many-to-many relation with join model Membership
between those two and there are methods to manages roles of a user in some house in the join model.
但我的问题是,用户只有一个房子并没有多少。所以,我总是要做user.houses.first得到他的房子(我已经成立了一个辅助的房子,这确实是),但设计不是很好,所以我一直试图把 HAS_ONE:会员
和 HAS_ONE:房子:通过=> :会员资格
而不是的has_many:成员
和的has_many:房子,:通过=> :会员资格
。但我每次我尝试从用户
。
But my problem is that a User has only one house and not many. So I always have to do user.houses.first to get his house (I've set up a helper house which does that) but the design is not good so I've tried to put has_one :membership
and has_one :house, :through => :membership
instead of has_many :memberships
and has_many :houses, :through => :memberships
. But I got an error each time I try to access house from User
.
这怎么可能建立这一个一对多的关系与连接表像我试图做?
How is it possible to set up this one-to-many relation with a join table like I was trying to do ?
感谢你在前进。
推荐答案
如果您要使用的一对多关系,那么联想应该的。
If you are going to use the one to many relation then association should be.
众议院的
的has_many :成员
的has_many :用户:通过=>:成员
has_many :users, :through => :memberships
用户的
HAS_ONE :会员
HAS_ONE :房子:通过=>:会员
has_one :house, :through => :membership
这篇关于特定的一个对多关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!