将 Rails 2 应用程序转换为 Rails 3,我必须更换 gem搜索逻辑 https://github.com/binarylogic/searchlogic。现在,使用 Rails 3.2.8 和 gemRansack https://github.com/ernie/ransack我想构建一个使用现有范围的搜索表单。例子:
class Post < ActiveRecord::Base
scope :year, lambda { |year|
where("posts.date BETWEEN '#{year}-01-01' AND '#{year}-12-31'")
}
end
据我所知,这可以通过定义自定义来实现掠夺者 http://rdoc.info/github/ernie/ransack/Ransack/Ransacker。遗憾的是,我没有找到任何有关此的文档。我在Post
class:
ransacker :year,
:formatter => proc {|v|
year(v)
}
但这不起作用:
Post.ransack(:year_eq => 2012).result.to_sql
=> TypeError: Cannot visit ActiveRecord::Relation
我尝试了一些变体ransacker
声明,但它们都不起作用。我需要一些帮助...
UPDATE:上述范围只是示例。我正在寻找一种方法来使用 Ransack 中的每个现有范围。 Ransack的前身MetaSearch中,有一个功能叫做search_methods
用于使用范围。兰萨克有不支持这个 https://github.com/ernie/ransack/issues/61开箱即用。
ransack 合并后开箱即用地支持它https://github.com/activerecord-hackery/ransack/pull/390 https://github.com/activerecord-hackery/ransack/pull/390。你应该声明ransackable_scopes
方法添加可见范围以进行搜查。
来自手册
继续上一节,按范围搜索需要定义一个白名单ransackable_scopes
在模型类上。白名单应该是符号数组。默认情况下,所有类方法(例如作用域)都会被忽略。范围将应用于匹配真实值,或者如果范围接受一个值,则应用于给定值:
class Employee < ActiveRecord::Base
scope :activated, ->(boolean = true) { where(active: boolean) }
scope :salary_gt, ->(amount) { where('salary > ?', amount) }
# Scopes are just syntactical sugar for class methods, which may also be used:
def self.hired_since(date)
where('start_date >= ?', date)
end
private
def self.ransackable_scopes(auth_object = nil)
if auth_object.try(:admin?)
# allow admin users access to all three methods
%i(activated hired_since salary_gt)
else
# allow other users to search on `activated` and `hired_since` only
%i(activated hired_since)
end
end
end
Employee.ransack({ activated: true, hired_since: '2013-01-01' })
Employee.ransack({ salary_gt: 100_000 }, { auth_object: current_user })
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)