Search code examples
mysqlruby-on-railsactiverecordruby-on-rails-5.1

Rails select is not giving the correct record while executing SQL


I am using TIMESTAMPDIFF in select using the below ActiveRecord query, but it is not giving the correct result.

1. 
Job.where(id: [1,2])
  .group(:user_level)
  .select("user_level, SUM((TIMESTAMPDIFF(MINUTE, start_datetime, end_datetime) - unpaid_break_time) / 60 * hourly_rate) AS income")

2.
Job.select("user_level, SUM((TIMESTAMPDIFF(MINUTE, start_datetime, end_datetime) -  unpaid_break_time) / 60 * hourly_rate) as income")
               .where(id: [1,2]).group(:user_level)

3.
Job.find_by_sql("
  SELECT user_level, SUM((TIMESTAMPDIFF(MINUTE, start_datetime,end_datetime) -  unpaid_break_time)/60 * hourly_rate) as income
  FROM jobs
  WHERE id IN (1,2)
  GROUP BY user_level
")

All three are giving same result i.e. [#<Job id: nil, user_level: 0.33e1>]

Expected: [{user_level: 0.33e1, income: 34}]

If I execute the SQL generated from above 3 in Workbench , I got the correct result. So, query is correct.

Also, If I use, pluck instead of select, I got the correct result but in Array as pluck returns array.

Job.where(id: [1,2]).group(:user_level)
   .pluck("user_level, sum(((TIMESTAMPDIFF(MINUTE, start_datetime,end_datetime) -  unpaid_break_time)/60 * hourly_rate)) as income")

So, how to use Select to get the expected output?

Note: In above query, id: 1,2 are just for example, the actual ids are different.


Solution

  • Did you try calling .income on the job (#<Job id: nil, user_level: 0.33e1>)?

    Rails takes all the returned columns and assigns them to the record, but only displays attributes that the model actually has in the default .inspect that the console shows.

    Calling .attributes on the job should also give you the income in a hash.