[英]What's the best way to include a LIKE clause in a Rails query?
What's the best way to include a LIKE clause in a Rails query ie something along the lines of (the completely incorrect):在 Rails 查询中包含 LIKE 子句的最佳方式是什么,即(完全不正确):
Question.where(:content => 'LIKE %farming%')
You'd use the syntax:您将使用以下语法:
Question.where("content LIKE ?" , "%#{farming}%")
If this is Rails 3 you can use Arel's matches
.如果这是 Rails 3,您可以使用 Arel 的
matches
。 This has the advantage of being database agnostic.这具有与数据库无关的优点。 For example:
例如:
Question.where(Question.arel_table[:content].matches("%#{string}%"))
This is somewhat clunky, but easily extracted to scopes, eg:这有点笨重,但很容易提取到范围,例如:
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(没有尝试过后者,但看起来很酷)他们都添加了这种类型的功能等等。
If you want really sexy conditions and and don't have problems with external dependencies, I highly recommend MetaWhere and 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%' }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.