Search code examples
ruby-on-railsrubyransack

No Ransack Search object was provided to search_form_for


I'm using the ransack gem, and it can't seem to find the search object, even though it's in my controller.

This is the index method

  def index
      if params[:q].present?
       @search = Patient.search(params[:q])
       @patients = @search.result
      else
       @patients = Patient.where(:user_id => params[:user_id])
      end
  end

This is the view form

<%= search_form_for @search do |f| %>
                <div class="field">
                    <%= f.label :name_cont, "Name" %>
                    <%= f.text_field :name_cont %>
                </div>
                  <div><%= f.submit %></div>
            <% end %>

Solution

  • You are conditionally setting search based on params[:q] which will never get generated because it relies on the form in your view.

    I would revise your code in your controller like this

    def index 
      @search = Patient.search(params[:q])
      @patients = @search.result
      if params[:q].blank?
        @patients = Patient.where(:user_id => params[:user_id])
      end
    end
    

    This way, you get your search prioritized if it's available, otherwise you scope it down to how you want it.