简体   繁体   中英

Access join table data in rails :through associations

I have three tables/models. User, Alliance and Alliance_Membership. The latter is a join table describing the :Alliance has_many :Users through :Alliance_Membership relationship. (:user has one :alliance)

Everything works ok, but Alliance_Membership now has an extra field called 'rank'. I was thinking of the best way to access this little piece of information (the rank).

It seems that when i do "alliance.users", where alliance is the user's current alliance object, i get all the users information, but i do not get the rank as well. I only get the attributes of the user model. Now, i can create a helper or function like getUserRole to do this for me based on the user, but i feel that there is a better way that better works with the Active Record associations. Is there really a better way ?

Thanx for reading :)

Your associations are all wrong - they shouldn't have capital letters. These are the rules, as seen in my other answer where i told you how to set this up yesterday :)

Class names: Always camelcase like AllianceMembership (NOT Alliance_Membership!)

table names, variable names, methods and associations: always underscored and lower case:

has_many :users, :through => :alliance_memberships

To find the rank for a given user of a given alliance (held in @alliance and @user), do

@membership = @alliance.alliance_memberships.find_by_user_id(@user.id)

You could indeed wrap this in a method of alliance:

def rank_for_user(user)
  self.alliance_memberships.find_by_user_id(user.id).rank
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM