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.

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.

Cydonia7
  • 3,744
  • 2
  • 23
  • 32

2 Answers2

2

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

HiteshRawal
  • 445
  • 2
  • 10
0

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
Yule
  • 9,668
  • 3
  • 51
  • 72