【问题标题】:Rails "assign_attributes" not assigning nested modelsRails“assign_attributes”未分配嵌套模型
【发布时间】: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


    【解决方案1】:

    在我看来,Strong Params(Rails 4 功能)可能正在剥离嵌套属性,并且由于没有它们您的验证失败,您将被重定向回编辑页面并出现错误,并且您的信用卡nested_attributes 现在为零。

    也许这会有所帮助。 https://stackoverflow.com/a/17532811/793330

    另外,save 和 update_attributes 也不是一回事。 Save 将保存整个对象,而 update 只会更改您传递给它的已更改的项目。有细微的差别,但还是有差别的。

    【讨论】:

      【解决方案2】:

      首先-您不需​​要include ActiveModel::Validations,因为它们带有ActiveRecord::Base

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

      如果您没有任何 attr_accessibleattr_protectedwith/without_protection 选项,我假设您正在使用

      创建正确的哈希
      {'credit_card_attributes' => {'card_number' => ''}}
      

      那么它看起来像是 Rails 中的某种错误。但同时我也只是检查了一下,似乎它工作正常。

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

      Wallet.new(hash_with_attributes).valid?
      

      它应该返回正确的钱包对象,其中包含嵌套的 credit_card 和错误。

      【讨论】:

        【解决方案3】:

        据我了解,assign_attributes 跳过了安全检查。

        In Rails 3, is there a difference between = and assign_attributes?

        【讨论】:

        • 该链接似乎相反(等号是跳过安全检查的功能)。而且我不明白为什么这会导致我看到的行为。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多