Really simple question - how do I do a search to find all records where the name starts with a certain string in ActiveRecord. I\'ve seen all sorts of bits all over the internet
Now it's 2012 I thought I'd throw in this update to narsk's answer.
named_scope
became simply scope
a while ago so the example becomes
class User
scope :name_starts_with, lambda {|str|
:conditions => ['lower(name) like ?', "#{str.downcase}%"]
}
end
Note I removed the first %
from narsk's solution as the OP is asking for a 'starts_with' not a 'contains' match.
Now you can do things like
User.name_starts_with("b").each do {|bs| puts bs.inspect}
bob = User.name_starts_with("bob").first
… etc
Note that scopes always return collections, never individual results. That threw me when I was first starting out with AR and I still manage to forget that every now and again.