user1092493
user1092493

Reputation: 1

has_many associative table methods in rails. How do I retrieve data from the association table?

I am creating an application that allows users to create teams, and then add members to them.

class User < ActiveRecord::Base
    has_many :memberships
    has_many :teams, :through => :memberships
end

class Team < ActiveRecord::Base
    has_many :memberships
    has_many :users, :through => :memberships
end

class Membership < ActiveRecord::Base
    belongs_to :team
    belongs_to :user
end

The Membership table contains ID, TEAM_ID, USER_ID, PERMISSIONS

I have access now to both Team.users and Team.memberships, but want I need to do is combine them so I can access the permissions column from the user like so:

Team.users.membership.permissions

OR

Team.users.permissions

But I can't figure it out even though I assume there is a simple answer. The has_many association between users and memberships works, as I am able to access the users from a team using Team.users. But I do not understand how or why the Permissions column from Membership is not also being joined onto the user object. Any help on this topic is much appreciated.

Upvotes: 0

Views: 430

Answers (1)

alony
alony

Reputation: 10823

As the users are connected to the team only by membership, isn't just Team.memberships.map(&:permissions) the code you need?

Upvotes: 2

Related Questions