简体   繁体   中英

Select2 tag re-ordering and 'acts as taggable on' gem

I have an options list in my params hash which I have re-ordered using select2 as such:

"option_list"=>["3,1,2"]

在此处输入图片说明

Unfortunately this seems to have no effect on the ordering of the tags saved by the gem:

Style.last.options
=> [#<ActsAsTaggableOn::Tag id: 20, name: "1">, #<ActsAsTaggableOn::Tag id: 18, name: "2">, #<ActsAsTaggableOn::Tag id: 17, name: "3">] 

Does anyone have any idea how to force reordering? Major service outage at github means I can't offer much explanation of how acts as taggable magic is happening..

Ok, Github is back, and now I have my answer:

To preserve the order in which tags are created use acts_as_ordered_taggable :

class User < ActiveRecord::Base
  # Alias for acts_as_ordered_taggable_on :tags
  acts_as_ordered_taggable
  acts_as_ordered_taggable_on :skills, :interests
end

@user = User.new(:name => "Bobby")
@user.tag_list = "east, south"
@user.save

@user.tag_list = "north, east, south, west"
@user.save

@user.reload
@user.tag_list # => ["north", "east", "south", "west"]

Anyone interested in replicating this process can do the following:

<%= m.input :option_list, :label => "Options", :input_html => { :multiple => true } %>

(above is simple_form DSL)

Then, for your JS, this will allow you to paste in comma delimited text and have it auto-tokenized... and have the ability to drag and drop the tags:

$("#style_option_list").select2({ width: '220px', tags:[], tokenSeparators: [","]})
$('body').on('paste', '.select2-input', function() {
  // append a delimiter and trigger an update
  $(this).val(this.value + ',').trigger('input');
});
$("#style_option_list").select2("container").find("ul.select2-choices").sortable({
    containment: 'parent',
    start: function() { $("#style_option_list").select2("onSortStart"); },
    update: function() { $("#style_option_list").select2("onSortEnd"); }
});

Don't forget to add acts_as_ordered_taggable_on :options to your Model

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