never_had_a_name
never_had_a_name

Reputation: 93176

How to search for a text with Active Record in Ruby on Rails 3?

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

Answers (5)

Macario
Macario

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

Amer
Amer

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

Upvotes: 2

skalee
skalee

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

Andrea Pavoni
Andrea Pavoni

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

Mohit Jain
Mohit Jain

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

Related Questions