【发布时间】:2011-08-13 14:34:59
【问题描述】:
在 Rails 查询中包含 LIKE 子句的最佳方式是什么,例如(完全不正确):
Question.where(:content => 'LIKE %farming%')
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 activerecord
在 Rails 查询中包含 LIKE 子句的最佳方式是什么,例如(完全不正确):
Question.where(:content => 'LIKE %farming%')
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 activerecord
你会使用语法:
Question.where("content LIKE ?" , "%#{farming}%")
【讨论】:
Question.where("content LIKE ? AND name is like ?", "%#{search1}%", "%#{search2}%")
如果这是 Rails 3,您可以使用 Arel 的 matches。这具有与数据库无关的优点。例如:
Question.where(Question.arel_table[:content].matches("%#{string}%"))
这有点笨拙,但很容易提取到范围,例如:
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
当然要加入“AND”,你可以链接范围。
编辑:虽然 +1 到 metawhere 和 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%' }
【讨论】:
Question.where {content.matches '%farming%'}