In my rails app, how can I query more than one fields from my database? Currently when user search for a product based on keywords, the query only get the name
field from db:
@products = @products.where("lower(name) LIKE ?", "%#{params[:search_free_text].downcase}%")
I need to include, description
and highlight
both in text format into the query. Thanks!!
This can be done with SQL like this:
@products = @products.where(
%w( name description highlight ).map { |column_name|
"lower(#{column_name}) LIKE :query"
}.join(' OR '),
query: "%#{params[:search_free_text].downcase}%")
I would say this is worth it to use a scope:
# in your app/models/product.rb
FULLTEXT_COLUMNS = %w( name description highlight )
scope :search, lambda { |query|
where(
FULLTEXT_COLUMNS.map { |c| "lower(#{c}) LIKE :query" }.join(' OR '),
query: "%#{query.downcase}%"
)
}
# in your controller:
@products = @products.search(params[:search_free_text])
您只需要遵循SQL
格式即可:
@products = @products.where("lower(name) LIKE :query OR description LIKE :query", query: "%#{params[:search_free_text].downcase}%")
Try this in a way make a scope in model Product
class Product < ActiveRecord::Base
scope :search_ndh, -> (name_text, desc_text, highlight_text){where("lower(name) LIKE :name OR description LIKE :desc OR highlight LIKE :high", name: "%#{name_text.downcase}%", desc: "%#{desc_text}%", high: "%#{highlight_text}%")}
end
and now use the scope
@products.search_ndh(params[:search_free_text].downcase, params[:search_description_text], params[:search_highlight_text])
or Arel ways
products = Product.arel_table
Product.where(products[:name].matches("%#{params[:search_free_text]}%").or(products[:description].matches("%#{params[:search_description_text]}%")).or(products[:highlight].matches("%#{params[:search_highlight_text]}%")))
or in scope by dynamic fields
class Product < ActiveRecord::Base
SEARCH_COLUMNS = [:name, :description, :highlight]
scope :search, lambda{ |q| where(SEARCH_COLUMNS.map{|c| self.arel_table[c].matches("%#{q}%").to_sql}.join(' OR '))}
end
and then
Product.search(params[:search_text])
it will generate
Product.search("das")
SELECT "products".* FROM "products" WHERE ("products"."name" LIKE '%das%' OR "products"."description" LIKE '%das%' OR "products"."highlight" LIKE '%das%')
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.