-->

No Ransack::Search object was provided to search_f

2020-03-24 09:38发布

问题:

I realise other people have asked about this error but it was to do with a different circumstance.

I have added the Ransack gem for rails 4 and bundled installed with:

gem "ransack", github: "activerecord-hackery/ransack", branch: "rails-4"

I have also edited my controller as follows (recipes_controller):

def index
if params[:tag]
  @all_recipes = Recipe.tagged_with(params[:tag])
else
  @all_recipes = Recipe.all
end
if signed_in?
  @user_recipes = current_user.recipes.order("created_at DESC").paginate(page: params[:page], :per_page => 10)
end
if params[:q]
  @q = Recipe.search(params[:q])
  @all_recipes = @q.result(distinct: true)
end
end

I have then added in the form as follows (recipes/index):

<%= search_form_for @q do |f| %>
  <%= f.label :name_cont %>
  <%= f.text_field :name_cont %>
  <%= f.submit %>
<% end %>

I am receiving the following error:

No Ransack::Search object was provided to search_form_for!

on this line:

<%= search_form_for @q do |f| %>

Would this be something to do with the install?

回答1:

Nicolas was right in that the error is coming from @q only being initialized when the request contains a "q" parameter. Which is why before you submit the form you get the error (no "q" parameter).

another way to get around this is initializing @q

in your application_controller

def set_search
@q=Recipe.search(params[:q])
end

in your recipes_controller before_filter :set_search



回答2:

The @q object is only initialized when the request contains a "q" parameter.

You should try to reduce the action index to the form of:

def index
  @q = Recipe.search(search_params)
  @recipes = @q.result(distinct: true).paginate(page: params[:page], per_page: 10)
end

private

def search_params
  default_params = {}
  default_params.merge({user_id_eq: current_user.id}) if signed_in?
  # more logic here
  params[:q].merge(default_params)
end