特定的一个对多关系 [英] Particular one-to-many relation

查看:117
本文介绍了特定的一个对多关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆