简体   繁体   中英

Query with alternating orders on ruby on rails

I have this code to query patients:

Patients.order(params[:sort])

how can I implement this so that each time this query will be executed the results are in an alternating order thus: (ascending -> descending -> ascending -> ...) ?

This code is implemented on a Controller on a Ruby on Rails application.

To implement this, you should store some key anywhere, right? Storing it in a database is not a good idea, because it's a +1 extra select and +1 extra update query for each page loading. If we store it anywhere on the server, eg, in Redis , it will be global for all users, or we will have to store as many keys as many users we have. So why not to store it on the side of a user? I think the best way is to store it in cookies and invert the key each time after the query. Or in the session.

sort_order = cookies[:sort_order] || 'asc'

Patients.order("#{params[:sort]} #{sort_order}")

cookies[:inverted_sort_order] = sort_order == 'asc' ? 'desc' : 'asc'

You can implemente this behaviour with a class variable, that increments every time you go to a particular action in your controller

#In your controller
@@hit_number ||= 0                  #This will set your hit_number the first time
@@hit_number = @@hit_number + 1     #Increment your hit_number

if (@@hit_number%2) == 0            #Switch for :asc or :desc 
  @my_order = :asc
else
  @my_order = :desc
end

@patients = Patients.order(name: @my_order)

And then, in your view the order will change every time it loads the view.

Note: This is not the best way to achieve this, but it is the easiest way for someone new to rails in my opinion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM