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 !