加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails“assign_attributes”不分配嵌套模型

发布时间:2020-12-17 03:16:07 所属栏目:百科 来源:网络整理
导读:我有两个具有以下结构的模型: 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 ...endc
我有两个具有以下结构的模型:

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测试我的应用程序的功能,我注意到一些奇怪的东西.如果我创建一个Hash,其属性不符合我的嵌套模型的验证标准(例如有一个nil card_number),然后尝试执行update_attributes调用,那么我在带有无效CreditCard的Wallet对象中返回的内容嵌套模型,以及相应的错误.这是正确的预期行为.

如果我采用相同的Hash并运行assign_attributes,然后保存(这是update_attributes应该做的所有事情,那么我将返回一个无效的Wallet对象,其中包含完全nil嵌套对象.为什么会这样?我如何更新所有嵌套属性值并检查错误而不保存?

解决方法

首先 – 您不需要包含ActiveModel :: Validations,因为它们带有ActiveRecord :: Base.

第二 – 是的update_attributes在内部使用assign_attributes所以基本上它应该按预期工作.

如果你没有任何attr_accessible,attr_protected,带/ without_protection选项,我假设你正在创建正确的哈希

{'credit_card_attributes' => {'card_number' => ''}}

然后它看起来像铁轨中的某种bug.但与此同时我只是检查它,似乎它工作正常.

如果您只想检查验证而不在测试中保存对象,那么只需运行即可

Wallet.new(hash_with_attributes).valid?

它应该使用嵌套的credit_card和错误返回正确的钱包对象.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读