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
Disclaimer: I am new to Ruby and Rails, and I am still trying to learn the Ruby Way to do things, but I have been coding for more than half of my life, and professionally for a decade. DRY is a concept with which I am very familiar. Here is how I implemented it. It is very similar to narsk's answer, which I think is also good.
# name_searchable.rb
# mix this into your class using
# extend NameSearchable
module NameSearchable
def search_by_prefix (prefix)
self.where("lower(name) LIKE '#{prefix.downcase}%'")
end
end
And then in your model:
class User < ActiveRecord::Base
extend NameSearchable
...
end
And then when you want to use it:
User.search_by_prefix('John') #or
User.search_by_prefix("#{name_str}")
One thing to call out:
Traditional relational databases aren't extremely good at satisfying these kinds of queries. If you are looking for a highly responsive implementation that will not kill your databases under load, you should probably use a solution that is tailored to the purpose instead. Popular examples include Solr or Sphinx, and there are many others as well. With this implementation, since you DRY, you could substitute the implementation with a separate indexer in just one place and you would be ready to rock.