Question

I have users and companies in a many to many relationship by a join table which has a column for user Role. I'm not sure if this is the best way to have the model set up.

Now each user can have different roles depending on the company, what is the best way to design and access user's role using ActiveRecord associations?

I would like to return via JSON the user's role based on their current company and default to something if their company is nil OR their role has not been set (nil).


Update:

What I've got now after reading Many-to-many relationship with the same model in rails? which is a bit different (many to many on itself).

CompaniesUser

belongs_to :company

belongs_to :user

Company

has_many(:companies_users, :dependent => :destroy)

has_many :users, :through => :companies_users

User

has_one :company

has_many(:companies_users, :dependent => :destroy)

has_many :companies, :through => :companies_users


Appreciate any advice as I'm just starting to learn this!

Was it helpful?

Solution

What you have above is correct, in terms of the ActiveRecord relationships. If you'd like to read more on the subject I believe this is the best source: http://guides.rubyonrails.org/association_basics.html

One problem I see there is that CompaniesUsers should be in singular form: CompanyUser, and then in all cases where you use :companies_users use: :company_users

I am assuming here that the current company of the User is the last one assigned.

Now in order to serialize in JSON format you should add the following in your User ActiveRecord:

    def serializable_hash(options = nil)
      options ||= {}

      h = super(options)
      if(defined?self.company_users.last and defined?(self.company_users.last).role)
        h[:role] = (self.company_users.last).role
      else
        h[:role] = 'default_value'
      end
    end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top