Home > Software engineering >  rails select2 autocomplete with ajax
rails select2 autocomplete with ajax

Time:02-10

I am a beginner in rails and I was looking for a solution for autocomplete in select2 with ajax. At first I was not able to find any clue then I asked my mentor to guide me and she told me flow of the process. I stated to find pieces of code in useful links on stack overflow but in whole it took me 6 hours of continuous efforts on searching and debugging and found what worked for me.

Here I'm sharing results of my efforts in hope to help someone who would come looking for autocomplete. It may contain some content that need to be improved.

problem statement: My task was to create a new coupon with name and value. and multiple products can be selected from drop-down for a coupon.

What I already have: i already have a product CRUD. now I have to associate it with coupon and display all products in select2 drop-down with ajax call.

What I did: I made the association where products belongs to coupon and coupon has many products. Now when user will select products from drop-down for new coupon, i will get all ids of products and update the new coupon id value in them.

Under coupon folder in _form.html.erb:
this is the select tag for products.It has id: 'autocomplete' that will let us call ajax on it.

<div >
  <%= label_tag 'Products', nil, class: 'col-sm-2 col-form-label'%></br>
  <div >
      <%= select_tag 'products',nil, class:"form-control", multiple: true, id: 'autocomplete'%>
  </div>
</div>

in select2.js file: write code to get params from user input and to pass them in controller for search and to append the searched results to select tag.

 document.addEventListener("turbolinks:load", function() {
      $('#autocomplete').select2({
        minimumInputLength: 3,
        placeholder: 'Search Products',
        ajax: {
          url: '/admin/coupons/product_search',
          dataType: 'json',
          data: function (params) {
            return { term: params.term };
          },
          processResults: function (result) {
            temp = result.map((obj)=>({text: obj.title, id: obj.id}))
            $('#autocomplete').append(temp);
              return { results: temp }
          }
        }
      });
    })

in coupon_controller.rb create an action named "product_search" as we are giving url for this in our ajax call.

  def product_search
    @products = Product.search_products(params[:term])
    render json: @products
  end

in product.rb write the function to search products for entered value by user:

def self.search_products(term)
    param = term
    where('lower(title) ILIKE :term', term: "%#{param.to_s.downcase}%")
 end

in routes.rb create a route for this action:

namespace :admin do
   ...
    resources :coupons do
      collection do
        get 'product_search'
      end
    end
  end

this is the whole code to implement autocomplete on select2.

CodePudding user response:

  •  Tags:  
  • Related