Search code examples
ruby-on-railsransack

Rails Ransack gem: search for multiple values by using only one select option


I use ransack gem and I have a select field status with multiple options

status_collection = %w(failed partial successful)
<%= search_form_for @q, :url => validation_path(:anchor => 'list'), :class => 'form-horizontal' do |f| %>
  <%= f.select :status_eq, options_for_select(Validation.status_collection, @status_eq_selection), {}, {:class => 'form-control'} %>
<% end %>

in my controller:

def show
    @q = Validation.where(report_id: params[:id]).search(params[:q])
   @validations = @q.result(distinct: true)
end

I'd like to merge the options failed and partial together in one select option failed so that if I search for failed then ransack should also search for partial and merge both search results.

How can I make ransack to search status attribute by select option failed and also for attribute partial so that I have a merged result of failed and partial by searching only for failed.


Solution

  • Based on our discussion in the comments, we can do it this way (not tested):

      before_action :adjust_ransack_params, only: [:show]
    
      private
    
      def adjust_ransack_params
        # Only change it if the status_eq is failed
        if params.dig(:q, :status_eq) == 'failed'
          params[:q].delete(:status_eq)
          params[:q][:status_in] = %w(failed partial)
        end
      end