mysql - Convert SQL query to Rails ActiveRecord query -
i have sql
query multiple left joins 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 tasks t left join tickets k on k.id = t.ticket_id left join installations on i.id = k.installation_id left join administrative_areas 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 1 = 1 , s.id = '#{district_id}' , t.status = '#{status}' , t.kind = 1 , t.completed_at >= '#{days_ago.days.ago.beginning_of_day.to_s(:db)}' , t.completed_at <= '#{days_until.days.ago.beginning_of_day.to_s(:db)}' group date(t.completed_at), s.id, s.name, u.first_name, u.last_name, t.assignee_id eos
i got 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"}]
sql
query.
but want stop using sql
query , switch activerecord
query , have converted activerecord
this:
task.joins("left join tickets k on k.id = tasks.ticket_id"). joins("left join installations on i.id = k.installation_id"). joins("left join administrative_areas 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 = ? , tasks.status = ? , tasks.kind = ? , tasks.completed_at >= ? , 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) completed_date, s.id district, assignee_id, u.first_name, u.last_name, count(tasks.id) completed_tasks'). group("date(tasks.completed_at), s.id, s.name, u.first_name, u.last_name, tasks.assignee_id")
but problem have here trying select
multiple columns in different tables, value activerecord
query returns belong task table alone. don't know doing wrong, maybe it's left joins
or select
[#<task status: 1, assignee_id: 215356, kind: 1>]
please, how convert above sql
query activerecord
query , same result?
you can use scuttle.io first result terrible, try configure associations in second tab. , please try avoid constructions this:
where("params.id = #{param[:id]}")
it unsecured (sql injection)!
Comments
Post a Comment