Search code examples
ruby-on-railssortingransack

Sorting buttons Ransack


I am using Rails 4 with Ransack to build simple search and sorting functionality. My intention is to use POST request instead of GET (because of limitations).

So I would have 4 buttons. One click on button sorts ASC, then second click sorts DESC. It is pretty much the same as http://railscasts.com/episodes/370-ransack?view=asciicast first example.

So far I have like this.

Controller:

  @search = Advertisement.search(params[:q])
  @ads = @search.result
  @search.sorts = ['height asc','age asc','price asc','votes asc'] if @search.sorts.empty?
      respond_with(@advertisements)

In view :

  Sort:
  <%= f.sort_fields do |s| %>
    <%= s.sort_select %>
  <% end %>

It looks like this :

enter image description here

Instead of selecting each time ASC or DESC in collection I want to do it with one button.

I searched on google similair questions but no one was exact like mine. Is there posibility to do so ? To use POST request not GET to sort with Ransack?

Or I have to switch back to GET request based sorting with limitations for user?

Thanks in advance!


Solution

  • I haven't already used ransack before, but this is the way that I would be to go:

    1. Create a master sort button, in normal html, something like this:

    <select id="master_sort">
      <option class="asc">ASC</option>
      <option class="desc">DESC</option>
    </select>

    1. "Bind" the action of your select code with jQuery. When the user change that value, it will change all the sub-sort button in cascade (with a simple jquery function)

    2. Hide the default sort selects with CSS.