ransack search form in header partial: No Ransack::Search object was provided to search_form_for

前端 未结 3 798
长情又很酷
长情又很酷 2021-02-04 14:30

First of all, I\'m new to RoR, so the answer may be obvious, in which case I apologize. I\'ve looked around and haven\'t found anything that helps.

I\'m trying to have

3条回答
  •  甜味超标
    2021-02-04 15:01

    As others have said, you need to utilize the ApplicationController's before_filter. Though ernie himself seems not to recommend this, the implementation is simple.

    First, use the advanced Ransack options to set your path for your search thusly

    #config/routes.rb
      resources :buckets do
        collection do
          match 'search' => 'buckets#search', via: [:get, :post], as: :search
        end
      end
    

    Second, update your BucketsController to include the following custom action:

    #controllers/buckets_controller.rb
      def search
        index
        render :index
      end
    

    Nothing yet out of the ordinary. If you currently try to search you will get the error from your original question. Your definition of the variable q is correctly implemented, but you will have to move it to the ApplicationController like so:

    #controllers/application_controller.rb
    before_filter :set_global_search_variable
    
      def set_global_search_variable
        @q = Bucket.search(params[:q])
      end
    

    Finally, update your search form to pass in the correct search options

    #layouts/_header.html.erb
    
        <% search_form_for @q, url: search_buckets_path, html: { method: :post }  do |f| %>
          <%= f.label :name_cont %>
          <%= f.text_field :name_cont %>
          <%= f.submit %>
        <% end %>
    

提交回复
热议问题