2014-03-28 49 views

回答

3

这应做到:

prefixes = ['mega', 'hyper', 'super'] 
sql_conditions = prefixes.map{ |prefix| "field ILIKE #{sanitize("#{prefix}%")}" }.join(' OR ') 
MyModel.where(sql_conditions) 

在我的IRB控制台:

prefixes = ['mega', 'hyper', 'super'] 
sql_conditions = prefixes.map{ |prefix| "field ILIKE #{ActiveRecord::Base.sanitize("#{prefix}%")}" }.join(' OR ') 
# => "field ILIKE 'mega%' OR field ILIKE 'hyper%' OR field ILIKE 'super%'" 

的替代,因为只有MySQL的:

prefixes = ['^mega', '^hyper', '^super'] # the^wildcard represents the start of line 
sql_conditions = "field RLIKE '#{prefixes.join('|')}'" # RLIKE is also known as REGEXP 
MyModel.where(sql_conditions) 
+0

谢谢!所有的好方法! – konyak

相关问题