Last active
August 29, 2015 14:15
-
-
Save withhawaii/f8f412c709ddaf46573f to your computer and use it in GitHub Desktop.
Using Arel and Scope to implement SQL "LIKE" statements
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Person < ActiveRecord::Base | |
scope :matches, lambda {|conditions| | |
where conditions.map {|key, value| | |
if value.is_a? Array | |
value.map {|v| arel_table[key].matches("%#{v}%")} | |
else | |
arel_table[key].matches("%#{value}%") | |
end | |
}.flatten.inject(:or) | |
} | |
end | |
#where last_name like "%Watts%" | |
persons = Person.matches(:last__name => "Watts") | |
#where last_name like "%Watts%" or last_name like "%Pena%" | |
persons = Person.matches(:last_name => ["Watts", "Pena"]) | |
#where (last_name like "%Watts%" or last_name like "%Pena%") or first_name like "%Bob%" | |
persons = Person.matches(:last_name => ["Watts", "Pena"], :first_name => "Bob") | |
#Chainining with other conditions: where (email = 'foo@doamin.com)' and (last_name like "%Watts%" or last_name like "%Pena%") | |
persons = Person.where(:email => "foo@domain.com").matches(:last_name => ["Watts", "Pena"]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Arel provides very powerful capabilities in database query, but calling arel_table[] seems ugly.
I think it is better place Arel based conditions inside of ActiveRecord scopes so that it will make your controllers clean.