简体   繁体   中英

Example - Select2 multiple AJAX code for Ruby on Rails 6/7 (without a Gem)

I was struggling to get a dynamic multiple choice Select2 based drop down working with my Rails 6/7 instance. Below is all the code you'll need. I got it working perfectly.

In my project my user was editing a story/article and adding multiple tags. As I had thousands of tags to choose from I wanted the look up to happen dynamically from the database. In addition I wanted them to be able to add new tags on the fly.

The controller method for the tag drop down:

def search
  name = tags_params[:search]
  result = Tag.where("name ILIKE '%#{ name }%'").order('LENGTH(name)').limit(10).map{ |x| {:id => x.id, :text => x.name} }
  render :json => {:results => result}
end

The controller method for the edit/new pages:

def edit
  @taggings = {}
  @taggings = @story.tags.map{|x| x.id}
  @tags = Tag.where(id: @taggings).or(Tag.where(public: true))
end

The route for JSON tag look up:

get "/tags/search" => "tags#search"

The Javascript/JS file:

$(document).ready(function() {
  $('.js-multiple').select2({
    minimumInputLength: 3,
    placeholder: 'Search',
    tokenSeparators: ',',
    tags: true,
    ajax: {
      url: '/jax/tags/search',
      quietMillis: 300,
      data: function (params) {
        var query = {
          search: params.term
        }
      return query;
    }
  }
});
});

In the HTML header or application.html.erb

<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.full.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />

The HTML ERB:

<%= collection_select(nil, "taggings", @tags, :id, :name, options = {:selected => @taggings}, html_options = {:multiple => "multiple", :class =>"js-multiple"}) %>

I hope this helps someone. Sean

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM