我有两个具有以下结构的模型:
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
调用,然后我在具有无效 CreditCard 嵌套模型的 Wallet 对象中返回的内容以及相应的错误。这是正确的、预期的行为。如果我使用相同的哈希并运行
assign_attributes
,然后 save
(这是 update_attributes 应该做的所有事情,然后我返回一个无效的 Wallet 对象,其中包含一个完全为零的嵌套对象。这是为什么?我如何更新所有嵌套的属性值并检查错误而不保存?
最佳答案
首先 - 你不需要 include ActiveModel::Validations
因为它们带有 ActiveRecord::Base
.
第二个 - 是 update_attributes
用途 assign_attributes
在内部,所以基本上它应该按预期工作。
如果您没有 attr_accessible
, attr_protected
, with/without_protection
选项,我假设您正在创建正确的哈希
{'credit_card_attributes' => {'card_number' => ''}}
那么它看起来像是 rails 中的某种错误。但同时我刚刚检查了它,它似乎工作正常。
在此之上,如果您只想检查验证而不在测试中保存对象,则只需运行
Wallet.new(hash_with_attributes).valid?
它应该返回带有嵌套 credit_card 和错误的正确钱包对象。
关于ruby-on-rails - Rails "assign_attributes"未分配嵌套模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15983443/