当Rails 5 ActiveRecord条件关联中条件不满足时,belongs_to拒绝

时间:2019-01-26 14:20:16

标签: ruby-on-rails activerecord ruby-on-rails-5 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

PaymentRequest可能仅包含相同货币的发票。并且满足条件,而调用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并引发异常。

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

1 个答案:

答案 0 :(得分:0)

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

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