Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can you use activerecord to find substring of a field? (quick & dirty keyword finder)

Suppose a database contains a field 'keywords' and sample records include: "pipe wrench" "monkey wrench" "crescent wrench" "crescent roll" "monkey bars"

is there a way in activerecord to find the records where the keyword field contains the substring "crescent"?

(It's just a quick and dirty lookup for a quick concept prototype)

like image 275
jpw Avatar asked Feb 18 '11 17:02

jpw


People also ask

What does ActiveRecord base do?

ActiveRecord::Base indicates that the ActiveRecord class or module has a static inner class called Base that you're extending.

What are ActiveRecord methods?

Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format, and many more.

Is ActiveRecord an ORM?

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

Yeah, just use a LIKE statement in MySQL.

In Rails 2.x:

Table.find(:all, :conditions => ['keywords LIKE ?', '%crescent%']) 

In Rails 3.x:

Table.where('keywords LIKE ?', '%crescent%').all 
like image 173
Pan Thomakos Avatar answered Sep 23 '22 21:09

Pan Thomakos


The Postgres database syntax would be:

YourModelName.where("yourFieldName like ?", "%" + yourSearchTerm + "%") 
like image 27
Martin Åhlin Avatar answered Sep 22 '22 21:09

Martin Åhlin