简体   繁体   中英

Convert SQL query to Rails ActiveRecord query

I have an sql query with multiple left joins that works fine:

query = <<-eos
      select date(t.completed_at) completed_date, s.id district, assignee_id, u.first_name, u.last_name, count(t.id) completed_tasks
      from tasks t
      left join tickets k on k.id = t.ticket_id
      left join installations i on i.id = k.installation_id
      left join administrative_areas a on i.ward_id = a.id
      left join service_areas s on s.id = a.service_district_id
      left join users u on u.id = t.assignee_id
      where 1 = 1
      and s.id = '#{district_id}'
      and t.status = '#{status}'
      and t.kind = 1
      and t.completed_at >= '#{days_ago.days.ago.beginning_of_day.to_s(:db)}'
      and t.completed_at <= '#{days_until.days.ago.beginning_of_day.to_s(:db)}'
      group by date(t.completed_at), s.id, s.name, u.first_name, u.last_name, t.assignee_id
      eos

I got this value after mapping: [{:completed_date=>"2015-07-11", :district=>"1339", :assignee_id=>"215371", :assignee_name=>nil, :first_name=>"John_9", :last_name=>"Ant", :completed_tasks=>"1"}] for the sql query.

But I want to stop using the sql query and switch to ActiveRecord query and I have it converted to ActiveRecord like this:

Task.joins("LEFT JOIN tickets k ON k.id = tasks.ticket_id").
        joins("LEFT JOIN installations i ON i.id = k.installation_id").
        joins("LEFT JOIN administrative_areas a ON i.ward_id = a.id").
        joins("LEFT JOIN service_areas s ON s.id = a.service_district_id").
        joins("LEFT JOIN users u ON u.id = tasks.assignee_id").
        where(["s.id = ? and tasks.status = ? and tasks.kind = ? and tasks.completed_at >= ? and tasks.completed_at <= ?", 26, "#{status}", 1, "#{days_ago.days.ago.beginning_of_day.to_s(:db)}", "#{days_until.days.ago.beginning_of_day.to_s(:db)}"]).
        select('date(tasks.completed_at) as completed_date, s.id as district, assignee_id, u.first_name, u.last_name, count(tasks.id) as completed_tasks').
        group("date(tasks.completed_at), s.id, s.name, u.first_name, u.last_name, tasks.assignee_id")

But the problem I have here is trying to do a select from multiple columns in different tables, the only value that the ActiveRecord query returns belong to the task table alone. I don't know what am doing wrong, maybe it's the left joins or the select

[#<Task status: 1, assignee_id: 215356, kind: 1>]

Please, how do I convert the above sql query to ActiveRecord query and get the same result?

You can use Scuttle.io the first result is always terrible, but try to configure associations in second tab. And please try to avoid constructions like this:

where("params.id = #{param[:id]}")

it is unsecured (sql injection)!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM