试试这个
以某种方式在模型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])
或其他方式
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%')