Search code examples
ruby-on-railsrubyruby-on-rails-5rails-activerecordactive-record-query

How to Write Complex Active Record Query in Rails


I need a Active Record Query to fetch an array. CRUDS for the models are working correctly but i need to fetch array in view file. I have following SQL syntax.

select FirstName from Person.Person
LEFT JOIN Sales.SalesPerson
ON Person.BusinessEntityID = SalesPerson.BusinessEntityID
LEFT JOIN Sales.SalesTerritory
ON SalesPerson.TerritoryID = SalesTerritory.TerritoryID
where SalesPerson.BusinessEntityID is null and SalesPerson.TerritoryID is null

What will be the Active Record Query syntax in rails? Any Idea?


Solution

  • Except for case and tables names your query should look something like this

    Person.left_joins(:sales_person, :sales_territory).
        where(sales_persons: {business_entity_id: nil, territory_id: nil}).
        pluck(:first_name)