samedi 10 octobre 2015

Implementing filters for search in my rails app

I want to create filters for my products in my app but I am not sure how to do that. On page products/ index I display a collection of my products I created a form like this :

  = form_tag products_path, method: 'get', :remote => true, class: 'form-inline min-marged-top' do ||
              .form-group
                = check_box_tag :price
                = check_box_tag :weight
                = button_tag(type: 'submit', value: "Go", class: 'btn btn-success')

the idea is that when the user ticks checkbox price or weight, the products are reordered by price / weight. This is an Ajax form and this is why I use :remote => true. First, I noticed that using the checkbox_tag, that the value of my checkboxes don't change when I tick them or not : they stay equal to 1. Shouldn't it be changing when the checkbox is ticked or not ? Assuming the value should be equal to 1 when the checkbox is clicked this is what I wanted to do in my product_controller in my method index (knowing I can also have a params[:content] sent through a search form) :

 def index
    if params[:content].present? && (params[:price] == "1")
      @products = Product.search(params[:content]).order(price: :desc).paginate(:page => params[:page], :per_page => 2)
      respond_to do |format|
        format.js {}
        format.html{ render :index }
      end
    elsif params[:content].present? && (params[:weight] == "1")
      @products = Product.search(params[:content]).order(weight: :desc).paginate(:page => params[:page], :per_page => 2)
      respond_to do |format|
        format.js {}
        format.html{ render :index }
    elsif params[:price] == "1"
      @products = Product.all.order(price: :desc).paginate(:page => params[:page], :per_page => 2)
      respond_to do |format|
        format.js {}
        format.html{ render :index }
    elsif params[:weight] == "1"
      @products = Product.all.order(weight: :desc).paginate(:page => params[:page], :per_page => 2)
      respond_to do |format|
        format.js {}
        format.html{ render :index }
    else
      @products = Product.all.paginate(:page => params[:page], :per_page => 2)
    end
  end

Is this the good way to implement filter by price & weight for products in my app ?




Aucun commentaire:

Enregistrer un commentaire