Ruby on Rails查询多个字段

时间:2016-03-18 07:40:27

标签: ruby-on-rails ruby postgresql

在我的rails应用程序中,如何查询数据库中的多个字段?目前,当用户根据关键字搜索产品时,查询仅从db:

获取name字段
@products = @products.where("lower(name) LIKE ?", "%#{params[:search_free_text].downcase}%")

我需要在文本格式中包含descriptionhighlight到查询中。谢谢!

3 个答案:

答案 0 :(得分:3)

这可以通过SQL完成:

@products = @products.where(
  %w( name description highlight ).map { |column_name| 
    "lower(#{column_name}) LIKE :query" 
  }.join(' OR '),
  query: "%#{params[:search_free_text].downcase}%")

我认为使用范围是值得的:

# 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])

答案 1 :(得分:1)

您只需按照SQL格式执行此操作:

@products = @products.where("lower(name) LIKE :query OR description LIKE :query", query: "%#{params[:search_free_text].downcase}%")

答案 2 :(得分:0)

试试这个  在某种程度上在模型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

现在使用范围

@products.search_ndh(params[:search_free_text].downcase, params[:search_description_text], params[:search_highlight_text])

或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]}%")))

或在动态字段范围内

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

然后

 Product.search(params[:search_text])

它会生成

Product.search("das")

SELECT "products".* FROM "products" WHERE ("products"."name" LIKE '%das%' OR "products"."description" LIKE '%das%' OR "products"."highlight" LIKE '%das%')