【问题标题】:No Ransack::Search object was provided to search_form_for没有向 search_form_for 提供 Ransack::Search 对象
【发布时间】:2014-02-16 13:39:36
【问题描述】:

我知道其他人问过这个错误,但它与不同的情况有关。

我添加了 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

然后我以如下形式添加(食谱/索引):

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

我收到以下错误

No Ransack::Search object was provided to search_form_for!

在这一行:

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

这与安装有关吗?

【问题讨论】:

  • 感谢@emaillenin 的编辑。有什么建议吗?
  • 用“ransack”替换“search”能解决问题吗? def index @q = Recipe.ransack(search_params) @recipes = @q.result(distinct: true).paginate(page: params[:page], per_page: 10) end

标签: ruby-on-rails ruby-on-rails-4 ransack


【解决方案1】:

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

另一种解决方法是初始化@q

在您的 application_controller 中

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

在你的 recipes_controller before_filter :set_search

【讨论】:

    【解决方案2】:

    @q 对象仅在请求包含“q”参数时才被初始化。

    您应该尝试将操作索引减少到以下形式:

    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
    

    【讨论】:

    • 嗨@Nicolas 感谢您的回答。我试图实现这一点,但我仍然遇到同样的错误。索引页面甚至不会加载,所以在提交表单之前我收到了错误。
    猜你喜欢
    • 2018-09-26
    • 1970-01-01
    • 2014-06-25
    • 2012-05-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    相关资源
    最近更新 更多