Search code examples
ruby-on-railsransack

Can I pass an argument and sort using ransack


"I want to display the exact ID at the top when searching. For example:

select * 
from user 
order by user.id = 25 DESC, created_at DESC;

How can I implement this using ransack?"


Solution

  • This can be done with the help of Arel::Table object. Arel is a library that is being used to help us to write complex SQL queries in a easier way. We can get an object by calling arel_table on the model:

    arel_user = User.arel_table
    

    Then we need to order the result of our ransack object by using arel_user:

    ransacked_object.result.order(arel_user[:id].eq(25).desc)