Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 387
never_had_a_name Avatar asked Jul 21 '10 23:07

never_had_a_name


People also ask

How do I search in Ruby on Rails?

Ruby on Rails doesn't actually have a module for search specifically. Active Record gives you a nice ORM to query data but doesn't have any helper methods to handle search. So we actually need to write a tiny bit of raw SQL and put that into Active Record's where method to make this work.

What does .save do in Ruby?

. save is an “Instance Method”, it returns either true or false depending on whether the object was saved successfully to the database or not. If the model is new, a record gets created in the database, otherwise the existing record gets updated.

What is ActiveRecord in Ruby on Rails?

What is ActiveRecord? ActiveRecord is an ORM. It's a layer of Ruby code that runs between your database and your logic code. When you need to make changes to the database, you'll write Ruby code, and then run "migrations" which makes the actual changes to the database.


2 Answers

 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 –

like image 131
Mohit Jain Avatar answered Oct 02 '22 15:10

Mohit Jain


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.

like image 25
skalee Avatar answered Oct 02 '22 14:10

skalee