您可以考虑使用Arel
。 Arel
是rails/activerecord的底层查询汇编程序(因此不存在新的依赖关系),并且在构建复杂查询时非常有用,因为它提供的深度比高级别ActiveRecord::QueryMethods
更深。
Arel
提供了大量的预测匹配器,包括您的案例matches_any
和matches_all
。这些方法采用Array
的String
秒,并使用Like
将它们分成单独的搜索条件。
例如,要搜索包含任何单词搜索,你可以使用所有考生:
class Candidate < ActiveRecord::Base
def self.search_for(term)
candidates = Candidate.arel_table
where(
candidates[:title].lower.matches_any(
term.split.map { |t| "%#{t.downcase}%" }
)
)
end
end
的search_for
最终的结果(因为“白凳子酒吧”的搜索项)为:
SELECT [candidates].*
FROM [candidates]
WHERE (
LOWER([candidates].[title]) LIKE '%white%'
OR LOWER([candidates].[title]) LIKE '%stool%'
OR LOWER([candidates].[title]) LIKE '%bar%')
这似乎是你在找什么。如果必须在所有方面与您可以改用matches_all
这将导致:
SELECT [candidates].*
FROM [candidates]
WHERE (
LOWER([candidates].[title]) LIKE '%white%'
AND LOWER([candidates].[title]) LIKE '%stool%'
AND LOWER([candidates].[title]) LIKE '%bar%')
See Here所有可用Arel
断言。
这增加了基本转义的好处,以避免SQL注入等事情。
您正在使用哪个数据库? – Gerry
这可能会有所帮助 - MySQL – Mark