1

I am trying to make next query with ActiveRecord and have no idea about how to achieve this SQL result without using find_by_sql call.

SELECT *
FROM table_x AS a,
    (SELECT locator, max(day_parsed) AS max_day
     FROM table_x
     WHERE day_parsed BETWEEN params[:day_from] AND params[:day_to]  
     GROUP BY locator) AS b
WHERE a.locator = b.locator
AND a.day_parsed = b.max_day

Any idea?

3
  • What's wrong with find_by_sql? Why bother converting a readable SQL query to a non-readable ActiveRecord code? Commented Feb 10, 2016 at 16:54
  • find_by_sql returns a Hash. Ideally I would like to create an ActiveRecord model based in this result. I tried with a postgresql view, but because I need the date range params I discarded to use DB views. What is wrong is that I cannot use the active_record associations Commented Feb 10, 2016 at 17:04
  • For example, I would like to use an scope based in this result. Commented Feb 10, 2016 at 17:26

1 Answer 1

2

For example, we have active record TableX and its table name is table_x, so the query will be:

from = params[:day_from]
to   = params[:day_to]

TableX.joins("JOIN (
                     SELECT locator, max(day_parsed) AS max_day
                     FROM table_x
                     WHERE day_parsed BETWEEN #{from} AND #{to}  
                     GROUP BY locator
                   ) as b ON b.locator = table_x.locator")
      .where("table_x.day_parsed = b.max_day")
Sign up to request clarification or add additional context in comments.

5 Comments

what are the values of params[:day_from] and params[:day_to]?
for example "20010101" and "20160301"
If I hardcode the params it works fine, but I am creating an scope with this query that accepts this two parameters
To ensure it works, I think you may convert params[:day_from] to DateTime first
I have edited your response with the changes I made. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.