将current_scopes传递给搜索
我正在使用非常有用的has_scope gem。 我有一个通过在链接中传递范围创建的索引页面。
在那个索引页面上,我可以查询current_scopes。
我在该页面上有一个非常标准的搜索范围搜索表单,但使用它会返回没有任何范围的结果。
如何将current_scopes传递给搜索? 我尝试使用隐藏字段但无法使其工作。 我想如果我可以在一个链接中传递范围,我应该能够以一种forms传递它们但是在谷歌搜索后我不确定这是真的。
搜索表单
{:method => :post} do |f| %>
指数法
def index @user = User.find_by_username(params[:user_id]) @search = apply_scopes(@user.collections).search(params[:q]) @search.sorts = 'created_at desc' if @search.sorts.empty? @collections = @search.result.paginate(page: params[:page]) end
使用Ransack 1.6+中的新function,您可以在Ransack搜索中引入范围,但首先需要将它们列入白名单,如下所示:
class Employee < ActiveRecord::Base scope :active, ->(boolean = true) { where(active: boolean) } scope :salary_gt, ->(amount) { where('salary > ?', amount) } # `ransackable_scopes` by default returns an empty array # ie no class methods/scopes are authorized. # For overriding with a whitelist array of *symbols*. # def self.ransackable_scopes(auth_object = nil) [:active, :salary_gt] end end
然后你可以像这样触发它们:
Employee.ransack({ active: true, hired_since: '2013-01-01' }) Employee.ransack({ salary_gt: 100_000 }, { auth_object: current_user })
您也可以按正常方式将它们添加到search_form_for。
我希望这有帮助。
您可以存储/检索当前session
的数据,而不是将其放入url参数中。
引用对问题的评论:
这是has_scope支持的原因:default,所以你可以给proc一个从session中检索的值:
has_scope :degree, :default => proc { |c| c.session[:some_value] }
您可以在操作URL中传递当前作用域:
<%= search_form_for @search, url: search_people_path(current_scopes), do |f| %>