没有Ransack :: Search对象已提供给search_form_for

我意识到其他人已经问过这个错误,但这与其他情况有关。

我已经为rails 4添加了Ransack gem,并且已经安装了捆绑:

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

我还编辑了我的控制器如下(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 

然后我在表单中添加如下(食谱/索引):

      

我收到以下错误

 No Ransack::Search object was provided to search_form_for! 

在这条线上:

  

这会与安装有关吗?

Nicolas是正确的,因为当请求包含“q”参数时,错误来自@q仅被初始化。 这就是为什么在您提交表单之前,您会收到错误(没有“q”参数)。

解决这个问题的另一种方法是初始化@q

在你的application_controller中

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

在recipes_controller before_filter :set_search

仅当请求包含“q”参数时,才会初始化@q对象。

您应该尝试将操作索引减少为以下forms:

 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