【问题标题】:belongs_to reject if condition not meets in Rails 5 ActiveRecord Conditional Associations如果条件在 Rails 5 ActiveRecord 条件关联中不满足,belongs_to 拒绝
【发布时间】: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


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-23
      • 2017-02-18
      • 1970-01-01
      相关资源
      最近更新 更多