-->

How to get Conditional Groups in Ransack?

2019-09-07 13:21发布

问题:

Using Railscast and Ransack demo code, I am able to build Advanced Search like this

The drop down "all/any" 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 am not able to get.

I saw the Ransack Demo example multiple times but it is using Rails 5 and I am not very clear with some 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>

回答1:

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

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 OR grouping vs AND grouping.



回答2:

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

You'll need some javascript to dynamically add condition groups. The rest is already covered by Ransack. Just clone the ransack demo repository and and play around. The only changes you need is on the front-end side where you're building conditions.

Works fine with Rails 4.2.