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
I would highly recommend the Searchlogic plugin.
Then it's as easy as:
@search = Model.new_search(params[:search])
@search.condition.field_starts_with = "prefix"
@models = @search.all
Searchlogic is smart enough, like ActiveRecord, to pick up on the field name in the starts_with
condition. It will also handle all pagination.
This method will help prevent SQL injection and also will be database agnostic. Searchlogic ends up handling the search differently depending on the database adapter you're using. You also don't have to write any SQL!
Searchlogic has great documentation and is easy to use (I'm new to Ruby and Rails myself). When I got stuck, the author of the plugin even answered a direct email within a few hours helping me fix my problem. I can't recommend Searchlogic enough...as you can tell.
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.