【发布时间】:2016-10-17 14:48:04
【问题描述】:
我使用select2 并想创建新标签然后保存它们。
我有@cost 和select2 的表单
<%= f.collection_select :product_ids, Product.all,:id, :name ,{include_hidden: false},{ multiple: true} %>
为了创建新产品,我有这个js code
$(document).ready(function () {
$('#cost_product_ids').select2({
tags: true,
tokenSeparators: [",", " "],
createProduct: function (product) {
return {
id: product.term,
text: product.term,
isNew: true
};
}
}).on("change", function (e) {
var isNew = $(this).find('[data-select2-tag="true"]');
if (isNew.length) {
$.ajax({
type: "POST",
url: "/product_new",
data: {product: isNew.val()}
});
}
});
});
保存新产品的控制器方法
def product_new
product = Product.find_by(name:params[:product])
Product.create(name:params[:product]) if !product
render json: :ok
end
cost create动作
def create
@cost = Cost.new(costs_params)
if @cost.save
flash[:notice] = t('added')
if params[:add_more].present?
redirect_back(fallback_location: root_path)
else
redirect_to @cost
end
else
render action: 'edit'
end
end
def costs_params
params.require(:cost).permit(:day, :amount, :description, :source,:tag_list,:product_ids=>[])
end
它工作正常,但是当我想用这个新创建的产品保存我的@cost 记录时,我只收到了没有 ID 的标签名称。
例如,我在 db 中有产品 water=>id:1,beer=>id:2,and create new juice tag,它有 id:3
在创建时有参数"product_ids"=>["1", "2", "juice"]
如何解决?
【问题讨论】:
-
您能否添加一些有关成本记录的信息,可能是成本控制器或要保存的操作?
-
更新@CdotStrifeVII
标签: ruby-on-rails select2