Oguz Bilgic
Oguz Bilgic

Reputation: 3480

Save order of accepts_nested_attributes_for

I recently upgraded my app to v4.2.4 from v4.2.0. It turns out that save orders have been changed for nested attributes. Is there a way to define which 'accepts_nested_attributes_for' is saved first. I am able to notice the change because each model has before_create callbacks.

Update:

Problem starts when we switch from v4.2.0 to v4.2.1.

Update 2: Why order matters?

Because we have a single sign up form for customer, which accepts_nested_attributes_for both creditcard and subscription. Order of creditcard and subscription callbacks matter because once the creditcards' before_create callback is called we can create the subscription remotely on stripe.

Update 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

Upvotes: 1

Views: 1078

Answers (1)

Walerian Sobczak
Walerian Sobczak

Reputation: 849

In order to save a Creditcard before a Subscription, you just need to change the order of associations' declaration.

So the Customer model should look like this:

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

    ...
end

Upvotes: 1

Related Questions