Metal
Metal

Reputation: 205

User relationship join in active record query

My User table is connected to Company via a user_company table. Now I want to retrieve the company name that user belongs to. Please can you suggest the query I should use?

User
has_many :companies, :through => :user_companies

Company
has_many :users, :through => :user_companies

User does not directly belong to company.

user.company.name gives an error. I want to find out the company name which the user belongs to.

Upvotes: 1

Views: 191

Answers (2)

Jatin Ganhotra
Jatin Ganhotra

Reputation: 7035

@user.companies will give you an array of all the companies that the user is associated with.
Now, you can simply iterate over the array and get the company's name for each of the companies.

company_names = []
@user.companies.each {|entry| company_names << entry.name}

This is when you don't have the company's name attribute in the user_companies table.
If you have it that way, you can simply get all the names by

UserCompany.where(:select=>"name", :user_id=> @user)

Upvotes: 0

pdu
pdu

Reputation: 10413

Since a user has multiple companies, it is user.companies. To get the names, you could do e.g. user.companies.map(&:name)

Upvotes: 1

Related Questions