Skip to content

Integration of ActsAsTaggableOn

coezbek edited this page Dec 7, 2021 · 1 revision

Question

How do I add a select field to search and manage tags with ActsAsTaggableOn gem?

Answer

Trestle.resource(:products) do

  form do
    tag_select :tag_list
  end

  controller do

    def tags
      if params[:q]
        render json: ActsAsTaggableOn::Tag.where("name LIKE ?", "%#{params[:q]}%").collect { |t| { id: t.id, text: t.name } }
      else
        render json: []
      end
    end

  end

  routes do
    get :tags, on: :collection
  end

end

trestle/custom.js

$(function() {

  $("#product_tag_list").select2({
    theme: 'bootstrap',
    allowClear: true,
    minimumInputLength: 2,
    containerCssClass: ':all:',
    dataType: 'json',
    ajax: {
      url: '/admin/products/tags',
      delay: 250,
      data: function(params) {
        return { q: params.term }
      },
      processResults: function (data, params) {
        return {
          results: $.map(data, function(value, index){
            return {id: value.id, text: value.text };
          })
        };
        cache: true
      }
    }
  });
});