【问题标题】:Rails select2 after create new tag i haven't id on create action创建新标签后的Rails select2我没有创建操作的ID
【发布时间】:2016-10-17 14:48:04
【问题描述】:

我使用select2 并想创建新标签然后保存它们。

我有@costselect2 的表单

<%= 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=&gt;id:1,beer=&gt;id:2,and create new juice tag,它有 id:3

在创建时有参数"product_ids"=&gt;["1", "2", "juice"]

如何解决?

【问题讨论】:

  • 您能否添加一些有关成本记录的信息,可能是成本控制器或要保存的操作?
  • 更新@CdotStrifeVII

标签: ruby-on-rails select2


【解决方案1】:

你不应该使用 id: product.term, 但是id: product.id,

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-12-04
    • 1970-01-01
    • 2015-04-23
    • 2016-05-15
    • 2013-11-23
    • 1970-01-01
    相关资源
    最近更新 更多