Ask A Question


You’re not receiving notifications from this thread.

How do I allow a multi-select to be sortable?

Thomas Bush asked in General

I have a ton of many-to-many relationships in a CMS I built for work. I am currently using Select2 3.5.3 to assign these relationships. This all works well. My issue is attempting the make them drag and drop sortable and store the result of this in the database.

I got the Select2 Drag and Drop Sorting section demo working in my forms, but I don't quite understand how I would make this dynamic like the rest of my select2 instances -- in my simple implementation I initialize select2 on anything with the .select2 class. I also don't understand how I would store order in the db.

I have an example below modified from an old Ryan Bates update function. In this example I am attempting to update the Case Study model relationship with the Site model. Case Study and Site have standard has-and-belongs-to-many relationships with each other.



  has_many :case_studies_sites
  has_many :case_studies, :through => :case_studies_sites


  has_many :case_studies_sites
  has_many :sites, :through => :case_studies_sites

Update Function I think it would be accomplished. One other important point to note: I have added a position:integer field to the case_studies_sites table.

  def select2_sort
    self.case_studies.each_with_index do |id, index|
      CaseStudiesSite.where(case_study_id: id).update_all({position: index+1})

Forms and JS


Here is an example of the sites form.

   <div class="form-group">
      <%= f.label :case_study, "Related Case Studies" %>
      <%= f.collection_select :case_study_ids, CaseStudy.all, :id, :title, {}, {class: 'select2 form-control', multiple: true} %>

And finally here is the coffee script I am currently using to run the basic select2.

$(document).on 'ready page:load', ->

Both the form fields and JS are currently set for the standards select2 (aka not sortable) as I have not figured out how to translate the select2 demo to these fields.

Join the discussion
Create an account Log in

Want to stay up-to-date with Ruby on Rails?

Join 83,453+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.