1
votes

I'm trying to model to get the user's current company role through associations in rail.

A user can have many companies and different status in each company.

How do I model so I can do something like User.first.current_company.status

I already have the User and Company tables.

In another words:

A has_many Bs

A has_many Cs

A has_one B through C

(There are many As that has_one B through C)

How to define this association?

4

4 Answers

1
votes

Given the following model schemas:

# app/models/user.rb
class User < ActiveRecord::Base
  has_many :companies
end

# app/models/company.rb
class Company < ActiveRecord::Base
  belongs_to :user
  has_one :status
end

# app/models/status.rb
class Status < ActiveRecord::Base
  belongs_to :company
end

The following relationships are valid:

status = Status.first
company = Company.first
user = User.first

company.status = status # Assign status to company

user.companies << company # Add company to user

user.companies.last.status == Status.first # Status of user's last company is the original status
#=> true
0
votes

In your User.rb model:

class User < ActiveRecord::Base
  has_many :companies
end

In your Company.rb model:

class Company < ActiveRecord::Base
  belongs_to :user
end

I'm assuming status is an attribute in your company table. With this setup you should be able to do the command you want.

0
votes

I would use the Rolify Gem to accomplish this.

class User < ActiveRecord::Base
    rolify
    has_and_belongs_to_many :companies

    def status(company)
        roles = [:manager, :supervisor, :line-level]
        status = []
        roles.each { |role| status << role if self.has_role? role, company }
        return status
    end
end

class Company < ActiveRecord::Base
    resourcify
    has_and_belongs_to_many :users
end

This would allow you to do...

@company = @user.companies.first
@user.status @company     #=> [:manager] An array assuming they can have many roles.

Using this gem allows you to place multiple roles on a single object and scoped to that object.

0
votes

Eventually I created a join table which belonged to all the different entities (A, B, C).

A can has_many B through that join table B can has_many C through that join table C can has_many A through that join table

A, B and C has_many of that join table

To get a B or C of A, I create a method to retrieve the record from the join table with A. Then use that record to return B or C.