Using multiple LIKE statements in an ActiveRecord Query - ruby-on-rails

I am fairly new to Rails. I have been builidng a search bar that goes through all of my products. I got it to work when I am only searching through either the name of the product or the description. But I would like the search term to be compared to both and the product to be displayed if either the name matches the search term or it matches the description.
This is my code at the moment:
if params[:q]
search = params[:q]
#products = Product.where("name LIKE ? OR description LIKE ?", "%#{search}%")
else
#products = Product.all
end
Right now I am getting an error: "Wrong Number of Bind Variable"
I have been trying to google for a solution but I havn't gotten lucky. I would reallz appreciate if someone could help me! Thanks so much.

If your variables in query have the same value, you can use named key:
#products = Product.where(
"name LIKE :search OR description LIKE :search", search: "%#{search}%"
)
If they different:
#products = Product.where(
"name LIKE :first_search OR description LIKE :second_search",
first_search: "%#{f_search}%", second_search: "%#{s_search}%"
)
or just use question marks:
#products = Product.where(
"name LIKE (?) OR description LIKE (?)", "%#{f_search}%", %#{s_search}%"
)

You need to provide search key twice. One for each ?
search_key = "%#{search}%"
#products = Product.where("name LIKE ? OR description LIKE ?", search_key, search_key)

Related

Ruby on Rails: Advanced search with two string in one search

I'm having trouble understanding advanced search with two string
pls help
error coms like:
undefined method `where' for #
<ActiveRecord::QueryMethods::WhereChain:0x007f2dcc0da5b0>
in the search model
search.rb
def search_books
books = Book.all
books = books.where{["name LIKE ?","%#{keywords}%"]}if keywords.present?
books = books.where{["category LIKE ?","%#{keywords}%"]}if keywords.present?
return books
end
Use like the below:
keywords = 'test'
with AND:
Book.where("name LIKE '%#{keywords}%' AND category LIKE '%#{keywords}%'") if keywords.present?
with OR:
Book.where("name LIKE '%#{keywords}%' OR category LIKE '%#{keywords}%'") if keywords.present?
But this usage is not safe. Read following warning from Rails documentation:
Building your own conditions as pure strings can leave you vulnerable
to SQL injection exploits. For example, Client.where("first_name LIKE
'%#{params[:first_name]}%'") is not safe.
If you wanted to use a scope for searching you could do something like this in your controller
def index
#books = Book.all
# scopes
if params[:keyword].present?
#books = #books.by_keyword(params[:keyword])
end
end
then in your model do the below
scope :by_keyword, ->(keyword) { where('name LIKE ? AND category LIKE ?', "%#{keyword}%", "%#{keyword}%").order(updated_at: :desc) if keyword.present? }

Search result is not displaying

I have an issue in searching records from the PostgreSQL with particular search keyword but no record is displaying here is the code
filter_text=params[:filter_search]
#outputs = Output.where("name LIKE '%#{filter_text}%'").order("name ASC")
Try this :
filter_text=params[:filter_search]
#outputs = Output.where("name LIKE ?","%#{filter_text}%").order("name ASC")
If you use ransack gem, it will allow you to use simple methods to search. Using ransack, you will only need to do this:
#outputs = Output.search(name_cont: params[:filter_search]).result.order("name ASC")
If you are going for case insensitive search go for ILIKE
filter_text = params[:filter_search]
#outputs = Output.where("name ILIKE ?", "'%#{filter_text}%'").order("name ASC")
Instead of:
filter_text=params[:filter_search]
#outputs = Output.where("name LIKE '%#{filter_text}%'").order("name ASC")
Try the following:
filter_text=params[:filter_search]
#outputs = Output.where(["name LIKE ?", "%#{filter_text}%"]).order("name ASC")
One easy way to search is to use Ransack. Which provides you an efficient search mechanism.

Rails - Active Record Search ".where" With Or Statement For Same Criteria

In my Rails app, I'm trying to let the user search for products using a key word or key phrase that matches the products' descriptions AND names.
According to the documentation, I have it written like so:
def productSearch
#results = 0
if !params[:searchInput].nil?
#results = 1
#searchInput = params[:searchInput]
#searchCriteria = "%#{params[:searchInput]}%"
#productList = Product.where("description like ? or name like ?", #searchCriteria, #searchCriteria)
end
end
What frustrates me is this line:
#productList = Product.where("description like ? or name like ?", #searchCriteria, #searchCriteria)
Is there a short-hand for matching both the description and name of the product to the same search criteria?
I'd like to also mention that I'm fairly new to Ruby on Rails and this is for a school project where I have to build an e-commerce website with my group, so help with this would be greatly appreciated.
Try:
#productList = Product.where("description like :search or name like :search", search: #searchCriteria)

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