How do I allow a multi-select to be sortable?
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.
Models
sites.rb
has_many :case_studies_sites
has_many :case_studies, :through => :case_studies_sites
case_study.rb
has_many :case_studies_sites
has_many :sites, :through => :case_studies_sites
Update Function
...how 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})
end
end
Forms and JS
sites/_form.html.erb
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} %>
</div>
sites.js.coffee
And finally here is the coffee script I am currently using to run the basic select2.
$(document).on 'ready page:load', ->
$('.select2').select2()
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.