我有两个型号,产品和生产商。生产者可以拥有许多产品,而产品属于生产者。 我现在正试图从搜索查询中获取所有记录,如下所示:
@products = Product.where("name like ? OR product.producer.name like ?", "%#{params[:q]}%", "%#{params[:q]}%")
这应返回product.name或product.producer.name与搜索字符串类似的所有产品。是否有短路轨道?
答案 0 :(得分:4)
您可以执行以下操作:
Product.includes(:producer)
.where('products.name LIKE ? OR producers.name LIKE ?', "%#{params[:q]}%", "%#{params[:q]}%")
你可以用它制作一个范围:
class Product < ActiveRecord::Base
scope :with_name_like, lambda { |name|
includes(:producer).where('products.name LIKE ? OR producers.name LIKE ?', "%#{name}%", "%#{name}%")
}
并像这样使用它:
@products = Product.with_name_like('Chair')