Association Help

Hello,

Let me setup the scenario

class User < ActiveRecord::Base
belongs_to :house
end

class House < ActiveRecord::Base
has_many :users
end

My question is, how can i implement the roomates association from the
user model? I’d like to do current_user.roomates and get a list of
current_user.house.users minus the current_user.

Thanks!

-Adam

@House.find(:first).users - [current_user]

in your controller somewhere.

Haven’t tested this but I’m thinking something like:

class User < ActiveRecord::Base
belongs_to :house

def roommates
User.find(:all,
:conditions => [‘house.id = ? and user.id <> ?’,
self.house, self],
:joins => “inner join houses on house.user_id =
users.id”)
end

end

On Jul 3, 6:06 pm, Adam W. [email protected]

@House.find(:first).users - [current_user]

in your controller somewhere.

I would put it in the models if i was to use a method like this

class User < AR::Base
belongs_to :house

def roomates
house.users - [self]
end
end

the problem with this aproach is that you cant do anything with the
rooomates apart from seeing them. you have no User.roomates <<
user.new or any of the Ar methods.

So… I would put it into the association, having house as a join
table between Users and Users… something on the lines (and note i
say on the lines because you would probably have to change the
associations you have to accomplish this.) of:

class user

has_many :roomates, :through => :house, :class_name => ‘User’

end