I have Rails 4 app with Ransack for search and sorting.
This far I managed to search and sort using Ajax. Works great.
First of all user selects region by clicking on checkbox. Ajax returns all records that are associated with selected region. Then user can sort just one of 5 available columns example height, weight and age..
My code so far.
Controller:
@search = @adver.search(params[:q])
@search.sorts = ['height asc','age asc','votes_for.size asc'] if @search.sorts.empty?
@advertisements = @search.result(distinct: true)
View: 1- Selects region
<%= search_form_for @search, :id=>"search_regions",:remote=>"true", url: advertisements_path, :method => :get do |f| %>
<% @regions.each_slice(20) do |slice| -%>
<div class="pull-left">
<ul>
<% slice.each do |region| -%>
<li>
<%= check_box_tag 'q[region_id_eq_any][]', region.id, false, :required => false, :id => region.id ,:html =>{:class=>"region-checkboxes"}, :onchange=>"$('#search_regions').submit();"%>
<label style="left: 0px;" for=<%=region.id%>><span><%=region.name%> </span>
</li>
<% end -%>
</ul>
</div>
<% end -%>
<%end%>
****2 - Sorts by columns****
<%= search_form_for @search, :class=>"search",:remote=>"true", url: advertisements_path, :method => :get do |f| %>
<%= f.text_field :name_or_phone_number_or_identifier_cont, :id=>"search-field-keyup",:class=>"form-control",:placeholder => "Meklēt pēc ID,vārda vai telefona numura" %>
<%= sort_link(@search, :height,"AUGUMS",{},{ :remote => true, :method => :get }) %>
<%= sort_link(@search, :age,"VECUMS", {hide_indicator: false},{ :remote => true, :method => :get }) %>
<%= sort_link(@search, 'votes_for.size',"REITINGS", {hide_indicator: false},{ :remote => true, :method => :get }) %>
<%end%>
Problem:
When I select region Ajax returns all associated records as expected. When I want to sort for example by height previous search clears and ajax sorts all records not just those that was in chosen region.
This is because I have separate search forms, but with the same name @ ? Any other way to achieve this. ?
Thanks in advance for your time.
This is because I have separate search forms
Yeah, you are absolutely right: the issue is that you have two different forms. By the time user makes decisions in the latter form, data from the first one is left above. Browser does not send information about region
along with height
or age
and this ends up in a wrong sorting/filtering.
What I would do here is attaching some javascript
function to handle the second form's submission. This function would obtain data from the second form, add value of selected region
from the first one manually, and send this to server.