不存在时插入Rails Build Association的唯一性

时间:2018-09-07 20:31:58

标签: ruby-on-rails activerecord orm

我在一个小型应用程序上有一些简单的逻辑。 我有一个叫做“ Oderne”的模型(ordene.rb):

class Ordene < ApplicationRecord
    has_many   :ordernes_detalles
end

enter image description here

详细信息称为(ordernes_detalle.rb):

class OrdernesDetalle < ApplicationRecord
    belongs_to :ordene
    belongs_to :refaccione
end

enter image description here

当我创建/更新记录关联时,它看起来像:

@order             = Ordene.new
    @order.folio       = SecureRandom.hex(4)
    @order.description = params[:description]
    @order.user_id     = 1
    @order.cliente_id  = params[:cliente_id]
    @order.reporte_id  = params[:reporte_id]
    params[:refaccione_id].each do |refaccion|
        @order.ordernes_detalles.build(
            :refaccione => Refaccione.find(refaccion),
            :tipo => 1
        )
    end
    if @order.save
        flash[:notice] = 'Orden creada correctamente'
        redirect_to action: 'index'
    else
        flash[:alert] = 'Error al crear la orden'
        redirect_to action: 'index'
    end

Al正常工作,并且记录看起来不错:

enter image description here

问题是要将其添加到我的“ OrdenesDetalle”模型中:

class OrdernesDetalle < ApplicationRecord
    belongs_to :ordene
    belongs_to :refaccione
    validates_uniqueness_of :ordene, scope: :refaccione
end

所以当我想使用以下方式更新记录时:

@order = Ordene.find(1)
        params[:refaccione_id].each do |refaccion|
            @order.ordernes_detalles.build(
                :refaccione => Refaccione.find(refaccion),
                :tipo => 1
            )
        end
        @order.save

控制台显示:

(0.3ms)  BEGIN
  ↳ app/controllers/ordenes_controller.rb:32
  OrdernesDetalle Exists (0.3ms)  SELECT  1 AS one FROM `ordernes_detalles` WHERE `ordernes_detalles`.`ordene_id` = 1 AND `ordernes_detalles`.`refaccione_id` = 1 LIMIT 1
  ↳ app/controllers/ordenes_controller.rb:32
  OrdernesDetalle Exists (0.2ms)  SELECT  1 AS one FROM `ordernes_detalles` WHERE `ordernes_detalles`.`ordene_id` = 1 AND `ordernes_detalles`.`refaccione_id` = 2 LIMIT 1
  ↳ app/controllers/ordenes_controller.rb:32
  OrdernesDetalle Exists (0.2ms)  SELECT  1 AS one FROM `ordernes_detalles` WHERE `ordernes_detalles`.`ordene_id` = 1 AND `ordernes_detalles`.`refaccione_id` = 3 LIMIT 1
  ↳ app/controllers/ordenes_controller.rb:32
   (0.1ms)  ROLLBACK

显示的查询显然不存在,但没有插入记录,我该如何在仍然重复记录的情况下插入该记录:

SELECT  1 AS one FROM `ordernes_detalles` WHERE `ordernes_detalles`.`ordene_id` = 1 AND `ordernes_detalles`.`refaccione_id` = 3 LIMIT 1

提前考虑。

0 个答案:

没有答案