Reputation: 143
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?
Upvotes: 9
Views: 8119
Reputation: 51
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
Upvotes: 1
Reputation: 11
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
Upvotes: 1
Reputation: 1058
Try using:
variable = "Fox"
Project.where("project_name like ?", "%#{variable}%")
Upvotes: 12
Reputation: 15089
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
.
Upvotes: 1