Ruby-on-rails 在 Rails 查询中包含 LIKE 子句的最佳方法是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7051062/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the best way to include a LIKE clause in a Rails query?
提问by Peter Nixey
What's the best way to include a LIKE clause in a Rails query i.e. something along the lines of (the completely incorrect):
在 Rails 查询中包含 LIKE 子句的最佳方法是什么,即类似于(完全不正确)的内容:
Question.where(:content => 'LIKE %farming%')
回答by Ammar
You'd use the syntax:
你会使用语法:
Question.where("content LIKE ?" , "%#{farming}%")
回答by numbers1311407
If this is Rails 3 you can use Arel's matches. This has the advantage of being database agnostic. For example:
如果这是 Rails 3,您可以使用 Arel 的matches. 这具有与数据库无关的优点。例如:
Question.where(Question.arel_table[:content].matches("%#{string}%"))
This is somewhat clunky, but easily extracted to scopes, e.g.:
这有点笨重,但很容易提取到范围,例如:
class Question
def self.match_scope_condition(col, query)
arel_table[col].matches("%#{query}%")
end
scope :matching, lambda {|*args|
col, opts = args.shift, args.extract_options!
op = opts[:operator] || :or
where args.flatten.map {|query| match_scope_condition(col, query) }.inject(&op)
}
scope :matching_content, lambda {|*query|
matching(:content, *query)
}
end
Question.matching_content('farming', 'dancing') # farming or dancing
Question.matching_content('farming', 'dancing', :operator => :and) # farming and dancing
Question.matching(:other_column, 'farming', 'dancing') # same thing for a different col
Of course to join with "AND" you could just chain the scopes.
当然,要加入“AND”,您可以将范围链接起来。
Edit: +1 to metawhere and squeel though (haven't tried latter but it looks cool) They both add this type of functionality and much more.
编辑:+1 到 metawhere 和 squeel(还没有尝试过后者,但看起来很酷)它们都添加了这种类型的功能等等。
回答by Mario Uher
If you want really sexy conditions and and don't have problems with external dependencies, I highly recommend MetaWhereand it's successor Squeel:
如果你想要真正性感的条件并且没有外部依赖的问题,我强烈推荐MetaWhere和它的继任者Squeel:
# MetaWhere
Question.where(:content.like => '%farming%')
# MetaWhere with operators overloaded
Question.where(:content =~ '%farming%')
# Squeel
Question.where { :content.matches => '%farming%' }
# Squeel with operators overloaded
Question.where { :content =~ '%farming%' }

