开发者

Particular one-to-many relation

I've got a Rails 3.1 app with a User model and a House model (this is like a group). I've set 开发者_StackOverflow中文版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.

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 ?

Thank you in advance.


If you are going to use the one to many relation then association should be.

House

has_many :memberships

has_many :users, :through => :memberships

User

has_one :membership

has_one :house, :through => :membership


I can't think of a way doing this with relations, however you could leave it as the plural and then just define house in users:

class User 
  has_many :memberships
  has_many :houses, :through => :memberships

  def house
    houses.first
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜