Search code examples
ruby-on-railswhere-clauserails-activerecordhas-manybelongs-to

searching records in rails include belongs_to or has_many


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?


Solution

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