Here’s my code example:
class User < ActiveRecord::Base
belongs_to :account
after_initialize :setup_account
def setup_account
self.account = Account.new
end
def email=(email)
self.account.email = email
super(email)
end
end
Now, the following call is failing:
User.new(email: 'hello@example.com')
Because this is executing the email= method before the setup_account method, where the account variable would be set.
How would you change this code to work as expected? I know the copying of email is a bad thing to do, but it could have been something else instead of a simple copy.
You can use the following. It doesn’t use any callbacks, but lazily creates an account or returns an existing one.
You also need to specify that you want to autosave the
accountassociation when you save the user object. Otherwise you would have to do it manually when updating an user record.