Pet*_*xey 22 activerecord ruby-on-rails ruby-on-rails-3
在Rails查询中包含LIKE子句的最佳方法是什么,即(完全不正确的):
Question.where(:content => 'LIKE %farming%')
Run Code Online (Sandbox Code Playgroud)
Amm*_*mar 42
你会使用以下语法:
Question.where("content LIKE ?" , "%#{farming}%")
Run Code Online (Sandbox Code Playgroud)
num*_*407 33
如果这是Rails 3,你可以使用Arel's matches.这具有与数据库无关的优点.例如:
Question.where(Question.arel_table[:content].matches("%#{string}%"))
Run Code Online (Sandbox Code Playgroud)
这有点笨重,但很容易提取到范围,例如:
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
Run Code Online (Sandbox Code Playgroud)
当然要加入"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%' }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27804 次 |
| 最近记录: |