1

I have this relationship :

class Organization < ActiveRecord::Base
  has_many :users
end

class User < ActiveRecord::Base
  belongs_to :organization
end

And I would like to gather a user's coworkers (i.e. who has joined the same organization).

The easy way would be to write a method like this :

def coworkers
  organization ? organization.users - [self] : []
end

But then I started thinking and felt like I can do this through a has_many relationship.

I ended doing this :

class User < ActiveRecord::Base
  belongs_to :organization
  has_many :coworkers, :through => :organization, :source => :users
end

which is working just fine except the user gets included in the coworkers.

What I'd like to know now is :

  • Is defining a method like I did a good way of achieving this ?
  • Is there a way to achieve this using has_many or any relationship (or anything else) without defining an actual method, and actually excluding the user ?
  • Which one would be optimal regarding the query performance, caching, or any important point I'm not aware of ?

Thanks !

Jeremy F.
  • 1,346
  • 12
  • 30

2 Answers2

3

You can add the :conditions option to the relation to exclude the current user. For example:

has_many :co_workers, :through => :organization, :source => :users, :conditions => ["user_id != ?", id]

This should do it for you!

Jeremy F.
  • 1,346
  • 12
  • 30
davidb
  • 8,884
  • 4
  • 36
  • 72
0

@davidb : Your answer was almost right, but the id in the conditions is not the one (the user's one) evaluated when calling user.coworkers.

This is the way to go :

  has_many :coworkers, :through => :organization, :source => :users, :conditions => lambda { ["users.id != ?", self.id] }
Jeremy F.
  • 1,346
  • 12
  • 30