Search code examples
ruby-on-railsrubyransack

Using multiple Ransack search forms in one page


I'm using several search_form_for on one page and I'm having a problem with the passed parameters. When one of the forms is submitted, its parameters override the parameters of other forms.

For example, need this on submit:

Parameters: {"q"=>{"search_cont"=>"qwerty", "by_discarded"=>"discarded"}, "f"=>{"search_cont"=>"asdfgh", "by_discarded"=>"active"}}

but getting it

Parameters: {"q"=>{"search_cont"=>"qwerty", "by_discarded"=>"discarded"}}

or it

Parameters: {"f"=>{"search_cont"=>"asdfgh", "by_discarded"=>"active"}}

View:

    <%= search_form_for @q, url: url, as: :q do |f| %>
          <%= f.search_field :search_cont, value: params.dig(:q, :search_cont), placeholder: 'Search' %>
          <%= f.select(:by_discarded, [['Active', 'active'], ['Discarded', 'discarded']], { selected: params.dig(:q, :by_discarded) }, { onchange: 'this.form.submit();' }) %>
    <% end %>
    ...
    <%= search_form_for @f, url: url, as: :f do |f| %>
          <%= f.search_field :search_cont, value: params.dig(:f, :search_cont), placeholder: 'Search' %>
          <%= f.select(:by_discarded, [['Active', 'active'], ['Discarded', 'discarded']], { selected: params.dig(:f, :by_discarded) }, { onchange: 'this.form.submit();' }) %>
    <% end %>

Controller:

@q = some_items.ransack(params[:q])
@q.sorts = 'sort_order asc' if @q.sorts.empty?
@pagy_q, @objects_q = pagy(@q.result, page_param: :page_q)

@f = another_items.ransack(params[:f], search_key: :f)
@f.sorts = 'sort_order asc' if @f.sorts.empty?
@pagy_f, @objects_f = pagy(@f.result, page_param: :page_f)

How to pass parameters from all forms when submitting one of the forms?


Solution

  • You have a couple of options:

    1. using js catching the submit event and then uniting the parameters of both forms
    2. unite both forms in one, but visually divide them into two. When you submit form you will be able to get parameters only from the form you submitted.