views:

171

answers:

4

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?

+2  A: 
 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 –

piemesons
Or in Rails 3 you'd write this as `Model.where(["name LIKE :tag", {:tag => tag}])` using the new finder syntax
bjg
but how do i tell RoR3 to search in ALL columns for that model not just in "name" column?
never_had_a_name
+1  A: 

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.

apeacox
+4  A: 

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.

skalee
so there is no way in Active Record to search for one string in every tables and their columns?
never_had_a_name
Searching in all tables could be performed with raw query like this: `SELECT 'table1' AS table_name, id FROM table1 WHERE c1 LIKE "%text%" OR c2 LIKE "%text%" UNION ALL SELECT 'table2' AS table_name, id FROM table2 WHERE c3 LIKE "%text%"`, but I wouldn't do that, it is totally awkward. If you are using MySQL, it has some full-text indexing capabilities - http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html - but I don't know how good is it. I don't know about full-text search support in other relational DBs. Recapitulating - AR won't help, use full-text indexing software if you can.
skalee
Just found a sec ago, it may help you http://snowgiraffe.com/rdocs/ar-extensions/classes/ActiveRecord/Base.html
skalee
+1  A: 

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

Amer
Not only Ferret. Sphinx's thinking-sphinx also integrates with AR nicely. Generally, using full-text indexing software is a good idea.
skalee
Ferret's kind of a pain in the rear. It's slow, it's prone to index corruption, and I had nothing but problems with it. thinking-sphinx is the way to go.
Chris Heald