9

Im trying to pull all records from a Project model that includes in the project_name the word 'Fox'. I can do an active record search and return specific project_names, like 'Brown Fox':

@projects = Project.where("project_name like ?", "Brown Fox")

But if I want to return all the names that INCLUDE 'Fox', this does not work unless the complete project name is 'Fox':

@projects = Project.where("project_name like ?", "Fox")

How do I do a search that returns all the objects with the word 'Fox' in the name?

JakeTy
  • 145
  • 2
  • 8

4 Answers4

12

Try using:

variable = "Fox"
Project.where("project_name like ?", "%#{variable}%")
Rudy Seidinger
  • 1,059
  • 13
  • 22
1

You can use the SQL % operator:

@projects = Project.where("project_name like ?", "%Fox%")

Note that if you want your query to return results ignoring the word case, you can use PostgreSQL ilike instead of like.

MurifoX
  • 14,991
  • 3
  • 36
  • 60
1

Did you try ransack ?

With ransack you can do something like

@projects = Project.search(:project_name_cont => "Fox")

If you think it is too much for what you need. you can use the % operator as MurifoX said

ovargas27
  • 11
  • 1
1

Here's a version that will allow you to handle any number of input words and to search for all of them within a name. I was looking for this answer and didn't find the more complicated case, so here it is:

def self.search(pattern)
  if pattern.blank?  # blank? covers both nil and empty string
    all
  else
    search_functions = []
    search_terms = pattern.split(' ').map{|word| "%#{word.downcase}%"}
    search_terms.length.times do |i|
      search_functions << 'LOWER(project_name) LIKE ?'
    end
    like_patterns = search_functions.join(' and ')
    where("#{like_patterns}", *search_terms)
  end
end
Jonah
  • 11
  • 2