如果条件不满足 Rails 5 ActiveRecord 条件关联,则belongs_to拒绝



>我有 2 个模型:

class PaymentRequest < ApplicationRecord
  has_many :invoices, ->(request) { with_currency(request.amount_currency) }
end

class Invoice < ApplicationRecord
  belongs_to :payment_request, optional: true
  scope :with_currency, ->(currency) { where(amount_currency: currency) }
end

付款请求可能只有相同货币的发票。它满足条件,而payment_request.invoices被调用。

我有不同的货币如下:

payment_request = PaymentRequest.create(id: 1, amount_currency: 'USD')
invoice = Invoice.create(amount_currency: 'GBP')

但是,如何拒绝以下内容?

# no validation here
payment_request.invoices << invoice
# the payment_request_id is set to 1
invoice.payment_request_id #=> 1

一种解决方案是添加has_many :invoices, before_add: :check_currency并引发异常。

有没有更好的解决方案来拒绝关联?

我实现了以下货币验证解决方案:

class PaymentRequest < ApplicationRecord
  has_many :invoices, ->(request) { with_currency(request.amount_currency) },
                      before_add: :validate_invoice
  monetize :amount_cents
  private
  def validate_invoice(invoice)
    raise ActiveRecord::RecordInvalid if invoice.amount_currency != amount_currency
  end
end

最新更新