Topic: Question on :through

Hello.

I'm having a bit of a problem modeling what has turned out to be a complex relationship.  I've got the basic has_many :through relationship down, but I am trying to add one more dimension to one end of the relationship.  Here's some of the code.

class Person < ActiveRecord::Base
  has_many :memberships
  has_many :groups, :through => :memberships
end

class Membership < ActiveRecord::Base
  belongs_to :person
  belongs_to :group
  belongs_to :rank
end

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :people, :through => :memberships
end

class Rank < ActiveRecord::Base
  has_many :memberships
end


I want to show rank of a person within a group (e.g. owner, assistant, communications), but I am not sure where to add this part of the relationship.  The code example has my guess, but I'd like to be able to do person.group.rank or something similar.

Re: Question on :through

You need to work through Membership to find a user's rank for a given group. For example:

person.memberships.find_by_group_id(group.id).rank

I recommend moving this into a method in the Person model.

def rank_for_group(group)
  person.memberships.find_by_group_id(group.id).rank
end

There are various ways to optimize this code, so keeping it in one place (in its own method) will allow you to easily do that if it's necessary.

Railscasts - Free Ruby on Rails Screencasts

Re: Question on :through

So I have my head in the right place with adding rank to a person in a group.  How would I assign a rank to a person?

Re: Question on :through

You need to assign a rank to a membership, not directly to a person. So to assign a rank in a group to a person you would create a membership model:

# assuming person, some_group, and some_rank are set
person.memberships.create(:rank => some_rank, :group => some_group)

Railscasts - Free Ruby on Rails Screencasts