本文介绍了没有向 search_form_for 提供 Ransack::Search 对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我为 rails 4 添加了 Ransack gem 并捆绑安装:

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

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

我还编辑了我的控制器如下(recipes_controller):

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 %>

我收到以下错误:

No Ransack::Search object was provided to search_form_for!

在这一行:

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

这与安装有关吗?

推荐答案

Nicolas 是对的,错误来自 @q 仅在请求包含q"参数时才被初始化.这就是为什么在提交表单之前您会收到错误消息(没有q"参数).

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).

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

another way to get around this is initializing @q

在您的 application_controller 中

in your application_controller

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

在你的 recipes_controller 中before_filter :set_search

in your recipes_controllerbefore_filter :set_search

这篇关于没有向 search_form_for 提供 Ransack::Search 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 22:42