Reputation: 93176
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?
Upvotes: 6
Views: 13345
Reputation: 2244
If you are deploying to heroku or don't mind dropping db agnosticism, postgres has full text search support. You won't need to run an additional service. Besides PG is the best OS database. http://tenderlove.github.com/texticle/
Upvotes: 3
Reputation: 2017
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
Upvotes: 2
Reputation: 12665
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.
Upvotes: 8
Reputation: 5311
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.
Upvotes: 3
Reputation: 43939
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 –
Upvotes: 11