Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
rails select2 autocomplete with ajax

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 class="mb-3 row">
  <%= label_tag 'Products', nil, class: 'col-sm-2 col-form-label'%></br>
  <div class="col-sm-10">
      <%= 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.

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda