Mattia
Mattia

Reputation: 179

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.

Upvotes: 0

Views: 149

Answers (2)

Alejandro Montilla
Alejandro Montilla

Reputation: 2654

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.

Upvotes: -1

Vasili
Vasili

Reputation: 905

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, e.g., 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'

Upvotes: 2

Related Questions