How do I search for a string in Ruby on Rails?
For example, all records with columns that contains "text".
Does Active Record have a method for it or do I have to use SQL "LIKE" for it?
How do I search for a string in Ruby on Rails?
For example, all records with columns that contains "text".
Does Active Record have a method for it or do I have to use SQL "LIKE" for it?
Model.find(:all, :conditions => ['name LIKE ?', "%#{tag}%"])
Where tag is your variable containing the string
as per @bjg comment:-
Or in Rails 3 you'd write this as
Model.where(["name LIKE :tag", {:tag => tag}])
using the new finder syntax –
you can also use Arel's 'match' method:
Model.match(:name => tag)
if you want to search in all columns, then you should write some extra code.
Sql like
may be very inefficient in some cases, for example in many cases in MySQL. I recommend using some full-text indexing software like Sphinx, Xapian or Lucene.
I think acts_as_ferret plugin would be perfect for your needs, this plugin allow you to configure easily very cool indexes like
ActsAsFerret::define_index( 'my_index',
:models => {
SomeModel => {
:fields => {
:name => { :boost => 4, :store => :yes, :via => :ferret_title },
:foo => { :store => :no, :index => :untokenized },
:baz => { :store => :yes, :via => :ferret_content }
}
}
} )
All acts_as_ferret indexes are configured in a single file, RAILS_ROOT/config/aaf.rb
find this tutorial it looks nice full text search in ruby on rails 3 (ferret)
Github source: http://github.com/jkraemer/acts_as_ferret/tree/rails3
The original plugin: http://ferret.davebalmain.com/trac/wiki/FerretOnRails