samedi 27 juin 2015

rails join query between two tables with similar field

I have 3 models

class Company < ActiveRecord::Base
  has_many : CompanyAccount
  has_many : CompanyContact
end

class CompanyContact < ActiveRecord::Base
  belongs_to : Company
end

class CompanyAccount < ActiveRecord::Base
  belongs_to : Company
end

As both the CompanyAccount and CompanyContact models belong to the Company model, they have a similar "company_id" field. I have retrieved some Accounts through a query:

@CompanyAccounts = CompanyAccount.where.not(balance:nil)

Now, using the common company_id field I am trying to retrieve all the data from my CompanyContacts table that belong to the same Company associated with the CompanyAccounts I queried above (in other words, I am trying to get the rows which have the same company_id). I have made several attempts using "joins" but everything failed so far. Could anyone give me what would be the appropriate syntax in this context? Thanks.

Aucun commentaire:

Enregistrer un commentaire