简体   繁体   中英

Rails Simple_form and Select2 with tags

I have a 'RootProduct' that belongs to a 'Subgroup2' and has_and_belongs_to_many 'Measure', among other relations. I'm using jQuery-select2 and Simple_form to build the forms. It works fine with simple associations but I cannot manage it to work with multiple tagging. Here is my model:

class RootProduct < ActiveRecord::Base

  attr_accessible :name, :subgroup2_id, :measure_ids
  has_many :market_products
  belongs_to :subgroup2
  validates_presence_of :name
  validates_uniqueness_of :name
  validates_presence_of :subgroup2
  validates_presence_of :measure_ids
  has_many :favorite_products
  has_many :users, :through => :favorite_products
  has_many :generic_market_produc_images, :dependent => :destroy, :class_name => 'GenericMarketProductImage'
  has_and_belongs_to_many :measures

end

Here is my form,

<body>
  <%= simple_form_for(@root_product) do |f| %>
    <%= f.error_notification %>
    <%= f.input :subgroup2_id, label: false %><br />
    <%= f.input :measure_ids, label: false, multiple: 'multiple' %><br />
    <%= f.input :name, label: false %><br />
    <div class="form-actions">
      <%= f.button :submit %>
    </div>

  <% end %>
</body>

And here is my select2 script,

$("#root_product_measure_ids").select2({
        width: "500px",
        placeholder: "Choose measures",
        tokenSeparators: [",", " "],
        multiple: true,
        ajax: {
          url: '/measures',
          dataType: "json",
          data: function(term, page) {
            return {
              q: term
            };
          },
          results: function(data, page) {
            return {
              results: data
            };
          }
        },
        initSelection: function(element, callback) {
            console.log("entrou 2");
            //console.log(element.val());
            var data = [];
            $(element.val().replace('[', '').replace(']', '').replace(/ /g,'').split(",")).each(function(i) {
                //console.log(this);
                $.ajax("/measures/"+this+".json", {
                dataType: "json"
                }).done(function(measure) {
                  data.push({
                    id: measure.id,
                    name: measure.name
                  });
                  callback(data);
                });
            }); 
        },
        formatResult: FormatResult,
        formatSelection: FormatSelection,
        dropdownCssClass: "bigdrop", // apply css that makes the dropdown taller
        escapeMarkup: function (m) { return m; },
        allowClear: true
      })
      .on("selected", function(e) { 
        MeasureSelected();
        })
      .on("removed", function(e) { 
        MeasureRemoved();
        })
      ;
    })

You can see from my console log that when the POST for the new 'RootProduct' is started, the array with the measure_ids is empty followed by the id's of the measures that should have gone inside the array.

在此处输入图片说明在此处输入图片说明 I'm missing something here. I've tried to tweak a lot of options with simple_form and select2 without success. Any suggestion would be very helpful.

I encountered this before. Here is my solution:

In root_product.rb, add the following:

class RootProduct < ActiveRecord::Base
  attr_accessible :ac_measure_ids
  attr_accessor :ac_measure_ids

  before_save :set_measures

  private

  def set_measures
    self.measure_ids = @ac_measure_ids.split(',')
  end

  def ac_measure_ids
    self.measure_ids.blank? ? "" : self.measure_ids.join(',')
  end

end

In form, replace

<%= f.input :measure_ids, label: false, multiple: 'multiple' %>

to

 <%= f.input :ac_measure_ids, label: false, multiple: 'multiple' %>

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