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

Ruby on-RailsActiverecord

Ruby on-Rails Problem Overview


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)

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

The Postgres database syntax would be:

YourModelName.where("yourFieldName like ?", "%" + yourSearchTerm + "%")

Solution 3 - Ruby on-Rails

It all depends on your DB. Is it Postgres? MySQL? MongoDB? Anything else?

With Postgres, you could use something like :

Rails 2.x => Model.find(:all, :conditions=>["models.keywords ~= ?", 'crescent'])
Rails 3.x => Model.where("models.keywords ~= ?", 'crescent')

You just have to find the right syntax for your DB / Rails / ActiveRecord version.

Solution 4 - Ruby on-Rails

I had a similar issue. I needed to see if there are keywords passed from conrolled input in the frontend component in the body of any questions in my questions table. Here is how I did it in my controller:

   def search
     input = params[:q]
       @questions = Question.all
       search_words = input.split(' ')
       @found_question = [];

       search_words.each do |word|
         @found_question << Question.where("questions.body LIKE ?", "%#{word}%")
     end
   end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjpwView Question on Stackoverflow
Solution 1 - Ruby on-RailsPan ThomakosView Answer on Stackoverflow
Solution 2 - Ruby on-RailsMartin ÅhlinView Answer on Stackoverflow
Solution 3 - Ruby on-RailschristianblaisView Answer on Stackoverflow
Solution 4 - Ruby on-Railsuser3916244View Answer on Stackoverflow