how to use LIKE in search in rails - ruby-on-rails

def self.search_by(search_term)
where("LOWER (course_name) LIKE :search", search_term: "%#{search_term}%")
end
this is my code, it seems LIKE query doesn't work at all

Your code where("LOWER (course_name) LIKE :search", search_term: "%#{search_term}%") isn't working because it's expecting an argument search but you're passing search_term. So, modify it to:
where("LOWER (course_name) LIKE :search", search: "%#{search_term}%")
now you're providing the same variable which it's expecting to get in "LOWER (course_name) LIKE :search".

#venues = Venue.where('name LIKE ?', "%#{#query}%")

scope :search_by, -> (search_term){ where("LOWER(course_name) LIKE ?", "%#{search_term.to_downcase}%")}
OR
def self.search_by(search_term)
where("LOWER(course_name) LIKE ?", "%#{search_term.to_downcase}%")
end

update your query to
where("LOWER (course_name) LIKE :search_term", search_term: "%#{search_term}%")
change the :search keyword with :search_term , you used alias :search in query but specify :search_term to assign search value.

The keyword ILIKE can be used instead of LIKE to match case-insensitive strings, so you don't have to use LOWER.
Also, the reason your query is not working is that you have to change the :search_term alias with :search.
def self.search_by(search_term)
where("course_name ILIKE :search", search: "%#{search_term}%")
end

Related

Rails - Where Like query is not returning results that are all capital letters [duplicate]

I'm using a LIKE clause in Ruby On Rails. When I try to search for records by typing "more" it doesn't return anything, but when I do with "More", then it returns the records which contains More keyword, so it seems like it behaves in a case-sensitive way.
Is it possible to make this case-insensitive?
Here is the query I am using currently:
Job.where('title LIKE ? OR duration LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%")
I assume you're using Postgres.
You can use ILIKE
Job.where('title ILIKE ? OR duration ILIKE ?', "%#{params[:search]}%", "%#{params[:search]}%")
Or a some tricky hack lower():
Job.where('lower(title) LIKE lower(?) OR lower(duration) LIKE lower(?)', "%#{params[:search]}%", "%#{params[:search]}%")
try something like this
def query_job(query)
job_query = "%#{query.downcase}%"
Job.where("lower(title) LIKE ? or lower(duration) LIKE ?", job_query, job_query)
end
query_job(params[:search])

How to make LIKE clause case-insensitive?

I'm using a LIKE clause in Ruby On Rails. When I try to search for records by typing "more" it doesn't return anything, but when I do with "More", then it returns the records which contains More keyword, so it seems like it behaves in a case-sensitive way.
Is it possible to make this case-insensitive?
Here is the query I am using currently:
Job.where('title LIKE ? OR duration LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%")
I assume you're using Postgres.
You can use ILIKE
Job.where('title ILIKE ? OR duration ILIKE ?', "%#{params[:search]}%", "%#{params[:search]}%")
Or a some tricky hack lower():
Job.where('lower(title) LIKE lower(?) OR lower(duration) LIKE lower(?)', "%#{params[:search]}%", "%#{params[:search]}%")
try something like this
def query_job(query)
job_query = "%#{query.downcase}%"
Job.where("lower(title) LIKE ? or lower(duration) LIKE ?", job_query, job_query)
end
query_job(params[:search])

Where clause on model associations

I have below where clause:
users.joins(:role).where("roles like :search OR email like :search OR first_name like :search OR last_name like :search",
search: "%#{params[:sSearch]}%")
I want to be able to query roles table name column.
This doesn't seem to work.
Is there a good way to achieve this containing all other conditions in the above?
try this
users.joins(:role).where("roles.name like :search OR email like :search OR first_name like :search OR last_name like :search",
search: "%#{params[:sSearch]}%")

Search multiple columns - Rails

I am currently writing a search method for my rails applications, and at the moment it works fine. I have the following in my game.rb:
def self.search(search)
if search
find(:all, :conditions => ['game_name LIKE ? OR genre LIKE ? OR console LIKE ?', "%#{search}%", "#{search}", "#{search}"])
else
find(:all)
end
end
Now that searches fine, but my problem is that if there is a record in game_name that has the word 'playstation' in it, it will finish the search there. It only returns that record, rather than all games that have 'playstation' stored in console. Now I understand this is because I have 'OR' in my conditions, but I don't know an alternative. 'AND' requires all the conditions to match or none return at all. What is an alternative I can use to AND and OR? Help would be much appreciated.
If there is a solution that has separate search boxes and entries, then that would be fine, I don't necessarily require the search to find it all based on one search form.
If I understand your question correctly, your SQL looks good to me for what you are trying to do. An OR clause will return all records that match in column1, column2, or column3. It doesn't stop at the first match. I do see an issue with your parameters in that the first you are using LIKE with % but in the second two you aren't, maybe that is where your issue is coming from.
Should this be your find (% around second and third search)?
find(:all, :conditions => ['game_name LIKE ? OR genre LIKE ? OR console LIKE ?', "%#{search}%", "%#{search}%", "%#{search}%"])
or better use DRY version (above will not work for Rails 4.2+):
Item.where('game_name LIKE :search OR genre LIKE :search OR console LIKE :search', search: "%#{search}%")
What if you have 15 columns to search then you will repeat key 15 times. Instead of repeating key 15 times in query you can write like this:
key = "%#{search}%"
#items = Item.where('game_name LIKE :search OR genre LIKE :search OR console LIKE :search', search: key).order(:name)
It will give you same result.
Thanks
I think this is a little bit of a cleaner solution. This allows you to add/remove columns more easily.
key = "%#{search}%"
columns = %w{game_name genre console}
#items = Item.where(
columns
.map {|c| "#{c} like :search" }
.join(' OR '),
search: key
)
A more generic solution for searching in all fields of the model would be like this
def search_in_all_fields model, text
model.where(
model.column_names
.map {|field| "#{field} like '%#{text}%'" }
.join(" or ")
)
end
Or better as a scope in the model itself
class Model < ActiveRecord::Base
scope :search_in_all_fields, ->(text){
where(
column_names
.map {|field| "#{field} like '%#{text}%'" }
.join(" or ")
)
}
end
You would just need to call it like this
Model.search_in_all_fields "test"
Before you start.., no, sql injection would probably not work here but still better and shorter
class Model < ActiveRecord::Base
scope :search_all_fields, ->(text){
where("#{column_names.join(' || ')} like ?", "%#{text}%")
}
end
I think this is a more efficient solution if you want to search an array of columns as I do.
First and most importantly you can add a private function to your model that creates a query template:
def self.multiple_columns_like_query(array)
array.reduce('') { |memo, x| #
unless memo == '' #
memo += ' or ' # This is the
end #
memo += "#{x} like :q" # core part
} #
end
Than you can use the function in your search function:
def self.search(query)
if fields = self.searched_fields && query
where multiple_like_query(fields), q: "%#{query}%"
end
end
Here you should also define self.searched_fields as an array of field names.

Rails3: Searching for Users by Second nad First name?

I want to write a simple search method in my User model where it checks agisnt the Second name and first name and returns matching users. I have this at the moment but throws an error:
def self.search(search)
if search
where("first_name like ? or second_name like ?", "%#{search}%")
else
all
end
end
the error is: wrong number of bind variables (1 for 2) in: first_name like ? or second_name like ?
How can i fix this?
Thanks
You have two ? which means the where method is expecting two arguments:
def self.search(search)
if search
where("first_name like ? or second_name like ?", "%#{search}%", "%#{search}%")
else
all
end
end
I'm not sure if you can streamline those likes to use one argument instead of the duplicate two, but you could clean it up a little:
def self.search(search)
if search
q = "%#{search}%"
where("first_name like ? or second_name like ?", q, q)
else
all
end
end
You can use
where("first name like :name or second name like :name", :name => "%foo%")

Resources