Ruby on Rails: Advanced search

前端 未结 3 741
太阳男子
太阳男子 2020-12-03 09:24

I\'m having trouble understanding the best way to make a advanced search form. I have had a good search on the internet, looking at some ways, but I can\'t get them to work,

3条回答
  •  醉梦人生
    2020-12-03 09:36

    A simple explanation can be found in this rails cast

    Basically, we have to test if the params contain a specific field and create the filter. See the example below:

    def find_products
      products = Product.order(:name)
      products = products.where("name like ?", "%#{keywords}%") if keywords.present?
      products = products.where(category_id: category_id) if category_id.present?
      products = products.where("price >= ?", min_price) if min_price.present?
      products = products.where("price <= ?", max_price) if max_price.present?
      products
    end 
    

    An alternative is Ransack. Ransack enables the creation of both simple and advanced search forms for your Ruby on Rails application

提交回复
热议问题