lundi 23 mai 2016

How to write the below SQL query in rails 3 ActiveRecord?

select * from
(
SELECT DISTINCT ON (table1.id) table1.*, table3.date_filed as date_filed
FROM
        table1 LEFT JOIN table2 ON table2.id = table1.some_id
        INNER JOIN table3 ON table2.id = table3.some_id
WHERE
    (
        status IN('Supervisor Accepted')
    )
    AND(table3.is_main)
)first_result
ORDER BY date_filed ASC LIMIT 25 OFFSET 0

Is there any way to run main/subset query in the database side through Active::record (Rails 3). I don't want run the first_result(First db query) and the order by on the top of the result(Second db query).

I tried the below:

    # First query run   
    first_result = Table1.select('DISTINCT ON (table1.id) table1.*, table3.date_filed').
    joins('LEFT JOIN table2 ON table2.id = table1.some_id'). # I don't want a association here
    joins('INNER JOIN table3 ON table2.id = table3.some_id').
    where('table3.is_main')

    # Second query run, WHICH is UGLY and not working properly
    Table1.where(id: first_result.collect(:&id)).
    order_by('date_filed ASC')
    page(page).
    per_page(per_page)

Aucun commentaire:

Enregistrer un commentaire