문제

I have two models, products and producers. A producer can have many products and a product belongs to a producer. I'm now trying to get all records from a search query like this:

@products = Product.where("name like ? OR product.producer.name like ?", "%#{params[:q]}%", "%#{params[:q]}%")

This should return all products where product.name or product.producer.name is like the search string. Is there a short rails way?

도움이 되었습니까?

해결책

You can do the following:

Product.includes(:producer)
        .where('products.name LIKE ? OR producers.name LIKE ?', "%#{params[:q]}%", "%#{params[:q]}%")

You can make a scope with it:

class Product < ActiveRecord::Base

  scope :with_name_like, lambda { |name| 
            includes(:producer).where('products.name LIKE ? OR producers.name LIKE ?', "%#{name}%", "%#{name}%") 
  }

And use it like this:

@products = Product.with_name_like('Chair')
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top