Search code examples
ruby-on-railsactiverecordmodelrails-activerecordhas-many

Rails 4 - How to get list of all companies from the "has_many -> belongs_to" relation?


I have this structure of models:

class OrganizationBlast < ActiveRecord::Base
  has_many :organization_blast_companies
end
class OrganizationBlastCompany < ActiveRecord::Base
  belongs_to :organization_blast
  belongs_to :company
end

How do I get a list of all companies in a blast? So far I am doing it this way:

organization_blast             = OrganizationBlast.find(params[:id])
organization_blast_companies   = organization_blast.organization_blast_companies.includes(:company)
organization_blast_companies.each do |organization_blast_company|
  puts organization_blast_company.company.name
  ...

I agree the naming conventions here are crazy.

However, is there a better way to obtain list of companies in the organization blast?

Thank you


Solution

  • I think you are looking for has_many :through association.

    Set up Models as given below:

    class OrganizationBlast < ActiveRecord::Base
      has_many :organization_blast_companies
      has_many :companies, through: :organization_blast_companies
    end
    class OrganizationBlastCompany < ActiveRecord::Base
      belongs_to :organization_blast
      belongs_to :company
    end
    
    class Company < ActiveRecord::Base
      has_many :organization_blast_companies
      has_many :organization_blasts, through: :organization_blast_companies
    end
    

    Then, just call organisation_blast.companies to fetch all companies associated with an OrganizationBlast object.

    organization_blast = OrganizationBlast.find(params[:id])
    organization_blast_companies = organization_blast.companies
    

    Refer: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association

    Hope it helps :)