【问题标题】:Save order of accepts_nested_attributes_for保存 Accepts_nested_attributes_for 的顺序
【发布时间】:2015-11-03 17:33:24
【问题描述】:

我最近将我的应用从 v4.2.0 升级到 v4.2.4。事实证明,嵌套属性的保存顺序已更改。有没有办法定义首先保存哪个“accepts_nested_attributes_for”。我能够注意到变化,因为每个模型都有 before_create 回调。

更新:

当我们从 v4.2.0 切换到 v4.2.1 时,问题就开始了。

更新 2:为什么顺序很重要?

因为我们有一个customer 的单一注册表单,其中accepts_nested_attributes_for 包括creditcardsubscriptioncreditcardsubscription 回调的顺序很重要,因为一旦调用了信用卡的 before_create 回调,我们就可以在条带上远程创建订阅。

更新 3:

class Customer < ActiveRecored::Base
    has_one :subscription
    has_many :creditcards

    accepts_nested_attributes_for :creditcards
    accepts_nested_attributes_for :subscription
end

class Creditcard < ActiveRecord::Base
    belongs_to :customer

    # needs to run before Subscription before_create callback
    before_create :create_stripe_creditcard
end

class Subscription < ActiveRecord::Base
    belongs_to :customer

    before_create :create_stripe_subscription
end

【问题讨论】:

  • 为什么顺序很重要?也许如果您解释了更多您想要做的事情,可能会有另一种解决方案?
  • @user2856118 更新了问题,谢谢。
  • 模型中的顺序会对代码产生影响。我假设您的关联顺序决定了首先运行哪个嵌套属性。为什么不尝试将 has_one :subscription 更改为 has_many :creditcards 之后。

标签: mysql ruby-on-rails ruby-on-rails-4 activerecord


【解决方案1】:

要在Subscription 之前保存Creditcard,您只需更改关联声明的顺序即可。

所以Customer 模型应该如下所示:

class Customer < ActiveRecored::Base
    has_many :creditcards
    has_one :subscription

    ...
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2017-03-30
    • 1970-01-01
    • 2016-05-13
    • 2018-04-26
    相关资源
    最近更新 更多