Ruby on Rails: Advanced search with two string in one search - ruby-on-rails

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? }

Related

Error in using WHERE for search function in Ruby on Rails

I made a controller to search something ,
but the result was weird:
My code:
def create
#word = searching_params[:word]
#searching = current_user.searchings.build(word: #word)
flash[:notice] = "New searching is performed!" if #searching.save
#users = User.where("firstname LIKE ? OR lastname LIKE ?", "%#{#word}%", "%#{#word}%")
#posts = Post.where("body LIKE ?", "%#{#word}%")
render :index
end
So, when i searched for a name: Mose Collins,
o, se, ose could get the result,
but m, c, co and others would give me nothing.
LIKE performs a case sensitive match. If you want to perform a case insensitive match in a somewhat polyglot fashion you can use the LOWER() SQL function:
#users = User.where("LOWER(firstname) LIKE ? OR LOWER(lastname) LIKE ?", "%#{#word.downcase}%", "%#{#word.downcase}%")
Postgres has a ILIKE function which is case insensitive:
#users = User.where("firstname ILIKE ? OR lastname ILIKE ?", "%#{#word.downcase}%", "%#{#word.downcase}%")
You can also use Arel to construct it instead of a SQL string:
class User < ApplicationRecord
has_many :favorite_jobs
def self.search(term)
where(
arel_table[:firstname].matches("#{name}").or(
arel_table[:lastname].matches("#{name}")
)
)
end
end
This approach is more portable and espcially shines if you want to built the query programatically.

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)

Using multiple LIKE statements in an ActiveRecord Query

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)

searching records in rails include belongs_to or has_many

I have two models, products and producers. A producer can have many products and a product belongs to a producer.
I'm now trying to get all records from a search query like this:
#products = Product.where("name like ? OR product.producer.name like ?", "%#{params[:q]}%", "%#{params[:q]}%")
This should return all products where product.name or product.producer.name is like the search string. Is there a short rails way?
You can do the following:
Product.includes(:producer)
.where('products.name LIKE ? OR producers.name LIKE ?', "%#{params[:q]}%", "%#{params[:q]}%")
You can make a scope with it:
class Product < ActiveRecord::Base
scope :with_name_like, lambda { |name|
includes(:producer).where('products.name LIKE ? OR producers.name LIKE ?', "%#{name}%", "%#{name}%")
}
And use it like this:
#products = Product.with_name_like('Chair')

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.

Resources