Home > database >  ActiveRecord join tables with Includes
ActiveRecord join tables with Includes

Time:06-02

How to execute the query above using Ruby ActiveRecord?

SELECT p.name, c.ios FROM public.projects p
INNER JOIN public.controls c
ON c.company_id = p.company_id

I tried

Project.includes(company::controls)
Project.joins(:company => controls)

But all failed

Project Model: { id, name, company_id, type, created_at, updated_at }
Company Model: { id, name, created_at, updated_at }
Control Model: { id, ios, android, macos, company_id, created_at, updated_at}

CodePudding user response:

If it is an INNER JOIN you need table1: :table2, assuming your models are correct you need the following

Project.includes(company: :controls)
Project.joins(company: :controls)
  • Related