【发布时间】:2019-01-26 14:20:15
【问题描述】:
我有 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 并引发异常。
有没有更好的方法来拒绝关联?
【问题讨论】:
标签: ruby-on-rails activerecord ruby-on-rails-5 belongs-to