问题描述
假设我的User类带有:email字段。假设我正在使用activeadmin管理用户。
制作一个过滤器,该过滤器返回与一个字符串匹配的电子邮件,例如史密斯,很简单。在 admin / user.rb
中,我只包括以下行
过滤器:email
这给了我一个完成任务的过滤器小部件。
但是,此过滤器不允许我搜索多个术语的交集。我可以搜索包含 smith的电子邮件,但不能搜索同时包含 smith和 .edu的电子邮件。
Google告诉我activerecord使用和具有高级模式,该模式允许进行多个词条搜索。
最简单的方法是获取多个术语搜索小部件变成activeadmin?
理想情况下,我想要一个小部件,它允许我输入 smith .edu
或 smith AND .edu
过滤包含这两个词的电子邮件。
有一个简单的解决方案使用ranasckable范围
因此在模型中放入类似的内容
类User< ActiveRecord :: Base
....
范围:email_includes,->(搜索){
current_scope = self
search.split.uniq.each do | word |
current_scope = current_scope.where('user.email ILIKE?',%#{word}%)
end
current_scope
}
def self.ransackable_scopes(auth_object = nil)
[:email_includes]
结束
结束
在此之后,您可以使用AA DSL添加过滤器
Like
过滤器:email_includes,如::string,标签:电子邮件
UPD
如果将 email_contains_any
更改为 email_includes
Let's say I've got User class with an :email field. And let's say I'm using activeadmin to manage Users.
Making a filter that returns emails that match one string, e.g. "smith", is very simple. In admin/user.rb
, I just include the line
filter :email
This gives me a filter widget that does the job.
However, this filter doesn't let me search for the intersection of multiple terms. I can search for emails containing "smith", but not for emails containing both "smith" AND ".edu".
Google tells me that activerecord uses Ransack under the hood, and the Ransack demo has an 'advanced' mode that permits multiple term searches.
What's the easiest way to get a multiple term search widget into activeadmin?
Ideally, I'd like a widget that would allow me to enter smith .edu
or smith AND .edu
to filter for emails containing both terms.
there is simple solution using ranasckable scopes
So put something like this in your model
class User < ActiveRecord::Base
....
scope :email_includes, ->(search) {
current_scope = self
search.split.uniq.each do |word|
current_scope = current_scope.where('user.email ILIKE ?', "%#{word}%")
end
current_scope
}
def self.ransackable_scopes(auth_object = nil)
[ :email_includes]
end
end
After this you can add filter with AA DSL
Like
filter :email_includes, as: :string, label: "Email"
UPD
should work if change email_contains_any
to email_includes
这篇关于ActiveAdmin:如何过滤与两个或多个搜索词匹配的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!