You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Johan Förberg edited this page Mar 26, 2015
·
5 revisions
Always use the bang methods on AR objects unless you have a reason not to. Even then, use the bang methods.
I found this code in master (since fixed):
after_create :create_profile_for_user
def create_profile_for_user
Profile.create(user: self)
end
What does this do? It tries to create a profile, silently ignoring any validation errors and then throws away the reference to the only object that has information about the error. Not what you want.
I cannot understand why the framework designer made this the default behaviour but there we are.
Instead, make it a habit to always use the save!, create!, update!, destroy! methods and explicitly catch the exception if that is what you want to do. The exception you want is usually ActiveRecord::RecordInvalid.
Or just let the exception pass to the controller where ApplicationController will do the right thing automatically for you (mostly, sort of... but you can help improve it!)