我有一个'RootProduct'属于'Subgroup2'和has_and_belongs_to_many'Measure',以及其他关系。我正在使用jQuery-select2和Simple_form来构建表单。它与简单的关联工作正常,但我无法管理它与多个标记。这是我的模特:
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
这是我的表格,
<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>
这是我的select2脚本,
$("#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();
})
;
})
从我的控制台日志中可以看到,当启动新的“RootProduct”的POST时,带有measure_ids的数组为空,后跟应该已经进入数组的度量的id。
我在这里遗漏了一些东西。我试图用simple_form和select2调整很多选项而没有成功。任何建议都会非常有用。
答案 0 :(得分:1)
在root_product.rb中,添加以下内容:
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
在表单中,替换
<%= f.input :measure_ids, label: false, multiple: 'multiple' %>
到
<%= f.input :ac_measure_ids, label: false, multiple: 'multiple' %>