wpp
wpp

Reputation: 7303

How to skip before_update if before_create was called

I'm trying to keep a user model "in sync" with a third party.

So in my User.rb:

before_create { ThirdParty.create!(user: self) }
before_update { ThirdParty.update!(user: self) }

The problem arises when I:

User.create!...

as both callbacks will be invoked (before_create then before_update).

This is how I got around this behaviour for now:

before_create {
 @before_create_called = true
 ThirdParty.create!(user: self)
}
before_update {
 return unless @before_create_called
 ThirdParty.update!(user: self)
}

But I'm not very confident/comfortable with this solution. Is there a better way to approach this?

EDIT

I'm sorry, of course this was my mistake, thanks to @Max Williams I wanted to get to the bottom of this, so for the curious:

I also had a:

after_create { A.new() }

Which somewhere in its bowels did this:

user.toggle(:active)

now it does this:

user.update_attributes(active: true).

and didn't realize that toggle skips validations and callbacks

Upvotes: 1

Views: 659

Answers (1)

Ben Chadfield
Ben Chadfield

Reputation: 36

Since you want to keep the third party synced on each save, but just want to change the action based on whether the record is being created or updated try:

before_save do
  self.new_record? ? ThirdParty.create!(user: self) : ThirdParty.update!(user: self)
end

Upvotes: 1

Related Questions