开发者

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

开发者 https://www.devze.com 2023-01-08 02:52 出处:网络
How do I search for a string in Ruby on Rails? For example, all reco开发者_开发百科rds with columns that contains \"text\".

How do I search for a string in Ruby on Rails?

For example, all reco开发者_开发百科rds 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 –


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.


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.


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/


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

0

精彩评论

暂无评论...
验证码 换一张
取 消