Skip to content

Instantly share code, notes, and snippets.

@withhawaii
Last active August 29, 2015 14:15
Show Gist options
  • Save withhawaii/f8f412c709ddaf46573f to your computer and use it in GitHub Desktop.
Save withhawaii/f8f412c709ddaf46573f to your computer and use it in GitHub Desktop.
Using Arel and Scope to implement SQL "LIKE" statements
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"])
@withhawaii
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment