Rails 3: rollback for after_create

Viewed 8914

I have an enrollment form.

When the user enrolls, the app is supposed to save the data in the enrollments table and in the users table. (I need this separation because the user's profile can change but the data he entered for that particular enrollment has to be archived. So even if later the user changes his last name, in the enrollment form I'll have his initial information.)

So I was thinking about saving data in the enrollments table then have a after_create call, like this...

class Enrollment < ActiveRecord::Base

  after_create :save_corresponding_user

  def save_corresponding_user
    user = User.new
    user.full_name = self.user_full_name
    user.email = self.user_email
    user.mobile_phone = self.user_mobile_phone
    user.save
  end
end

The issue is, what if saving the user fails for any reason. How can I rollback and destroy the just saved data from the enrollments table?

4 Answers
Related