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?
after_create is a part of the transaction saving the current model. Therefore, if your code crashes or if after_create returns false, it should rollback the current transaction and invalidate the
enrollmentsaving.If you want to simulate this, add this to your after_create and see if everything works as expected :