简体   繁体   English

Ruby on Rails查询多个字段

[英]Ruby on Rails query more than one fields

In my rails app, how can I query more than one fields from my database? 在我的Rails应用程序中,如何查询数据库中的多个字段? Currently when user search for a product based on keywords, the query only get the name field from db: 当前,当用户基于关键字搜索产品时,该查询仅从db获取name字段:

@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. 我需要在查询中包括, descriptionhighlight两种文本格式。 Thanks!! 谢谢!!

This can be done with SQL like this: 可以使用以下SQL来完成:

@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 尝试在模型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 或Arel方式

  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%')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM