【发布时间】:2013-04-05 16:39:27
【问题描述】:
我有两个具有以下结构的模型:
class Wallet < ActiveRecord::Base
include ActiveModel::Validations
has_one :credit_card
accepts_nested_attributes_for :credit_card
validates :credit_card, :presence => true
validates_associated :credit_card
...
end
class CreditCard < ActiveRecord::Base
include ActiveModel::Validations
belongs_to :wallet
validates :card_number, :presence => true
validates :expiration_date, :presence => true
...
end
我正在使用 RSpec 测试我的应用程序的功能,我注意到一些奇怪的东西。如果我创建了一个属性不符合我的嵌套模型的验证标准的哈希(例如具有 nil card_number),然后尝试执行 update_attributes 调用,那么我在 Wallet 对象中返回的内容带有无效的 CreditCard 嵌套模型,以及相应的错误。这是正确的预期行为。
如果我采用相同的 Hash 并运行 assign_attributes,然后运行 save(这就是 update_attributes 应该做的所有事情,那么我会返回一个无效的 Wallet 对象,其中包含一个完全为零的嵌套对象。为什么会这样?以及如何在不保存的情况下更新所有嵌套属性值并检查错误?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 validation nested-attributes