我有以下课程:
account
has_many :orders
has_many :payment_methods
order
belongs_to :account
has_one :payment
payment
belongs_to :order
belongs_to :payment_method
payment_method
belongs_to :account
has_many :payments
帐户有订单和付款方式。付款是订单和付款方式的结合。我尝试对付款进行验证,以确保付款方式属于下订单的帐户。
payment
validate :payment_method_belongs_to_account
def payment_method_belongs_to_account
if payment_method.account != order.account
# add error
end
end
我遇到的麻烦是当我在订单下创建付款作为嵌套对象时:
account = Account.new
order = Order.new(account: account)
payment_method = PaymentMethod.new(account: account)
order.payment.build(payment_method: payment_method)
if order.payment.valid?
# I never get here
end
通过在订单下将付款创建为嵌套对象,payment.order
为零,因此payment.order.account
失败。
如何解决此问题?