decent_exposure每次都会创建双重条目

时间:2014-09-06 21:56:29

标签: ruby-on-rails ruby nested-forms nested-attributes

我正在使用decent_exposure gem和cocoon gem来嵌套表单,并且在每次创建或更新后我都会收到重复的条目。我究竟做错了什么? X_X

控制器

class Admin::DealsController < ApplicationController
  expose :deals
  expose :deal, attributes: :deal_params

  def create
    if deal.save
      redirect_to [:admin, deal], notice: 'Deal was successfully created.'
    else
      render :new
    end
  end

  def update
    if deal.update(deal_params)
      redirect_to [:admin, deal], notice: 'Deal was successfully updated.'
    else
      render :edit
    end
  end

  private

  def deal_params
    params.require(:deal).permit :title, :end_date,
                                 deal_variants_attributes: [:id, :title, :description, :price, :discount, :_destroy]
  end
end

模型

class Deal < ActiveRecord::Base
  has_many :deal_variants

  accepts_nested_attributes_for :deal_variants, reject_if: :all_blank, allow_destroy: true
end

提前致谢!

1 个答案:

答案 0 :(得分:0)

我今天遇到了同样的问题,这是我的解决方案和解释:

这是因为decent_exposure已经为您设置了必需的属性,当您调用.update(deal_params)时,它会复制条目,因为DealVariant的第一个实例是set by decent_exposure,第二个是set by .update(deal_params)致电。您需要做的是在.savecreate操作中使用简单的update方法。