How to get conditional groups in Ransack?

Using Railscast and Ransack demo code, I can build an advanced search like this

enter image description here

The all / any dropdown comes from <% = f.combinator_select%> and it works, but I need conditional groups with (X and Y) OR (A and B) AND (M OR N), etc., which I can’t get.

I have repeatedly seen the Ransack Demo example, but it uses Rails 5, and I do not really understand part of it.

Here is my code in Rails 4, can you tell me how to get conditional grouping?

routes.rb

resources :data do collection do get :search post :search, to: 'data#search' end end 

data.rb

  def search @search = Data.search(params[:q]) @datum = @search.result(:distinct=>true).paginate(page: params[:page], per_page: 10) if params[:q].nil? @datum = Prospect.where(:id => 0).paginate(page: params[:page], per_page: 10) end @page = params[:page] || 0 @pids = @search.result(:distinct=>true).pluck(:id) @search.build_condition end 

search.html.erb

 <div class="row"> <div class="col-lg-10"> <div class="form_search"> <%= search_form_for @search, url: search_data_index_path, html: { method: :get, class: "data_search" } do |f| %> <%= f.condition_fields do |c| %> <%= f.combinator_select %> <%= render "condition_fields", f: c %> <% end %> <p><%= link_to_add_fields "Add Conditions", f, :condition %></p> <br> <div class="actions"> <%= f.submit "Search", :class => "btn btn-primary" %> </div> <% end %> </div> </div> </div> 

_condition_fields.html.erb

 <div class="field"> <%= f.attribute_fields do |a| %> <%= a.attribute_select associations: [:user, :data] %> <% end %> <%= f.predicate_select %> <%= f.value_fields do |v| %> <%= v.text_field :value %> <% end %> <%= link_to "remove", '#', class: "remove_fields" %> </div> 
0
source share
2 answers

In the Ransack documentation, your method in data.rb should look like this:

 def search @search = Data.search(params[:q].try(:merge, m: 'or')) @datum = @search.result(:distinct=>true).paginate(page: params[:page], per_page: 10) if params[:q].nil? @datum = Prospect.where(:id => 0).paginate(page: params[:page], per_page: 10) end @page = params[:page] || 0 @pids = @search.result(:distinct=>true).pluck(:id) @search.build_condition end 

to use the OR or VS grouping.

0
source

In the latest Ransack demo, you can see that condition groups are available.

You will need some javascript to dynamically add condition groups. The rest is already covered by Rankak. Just clone the ransack demo repository and play. The only changes you need are the outside on which you build the conditions.

Works great with Rails 4.2.

0
source

Source: https://habr.com/ru/post/1261383/


All Articles