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?
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.
. 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? 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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With