gpt4 book ai didi

ruby-on-rails - 没有 Ransack::Search 对象被提供给 search_form_for

转载 作者:行者123 更新时间:2023-12-01 02:19:45 25 4
gpt4 key购买 nike

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

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

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

我还编辑了我的 Controller 如下(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| %>

这与安装有关吗?

最佳答案

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

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

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

在你的 recipes_controller before_filter :set_search

关于ruby-on-rails - 没有 Ransack::Search 对象被提供给 search_form_for,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21351680/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com