Skip to content

Instantly share code, notes, and snippets.

@benshimmin
Created March 6, 2014 23:20
Show Gist options
  • Save benshimmin/9401836 to your computer and use it in GitHub Desktop.
Save benshimmin/9401836 to your computer and use it in GitHub Desktop.
How to raise a validation error in Rails after save
# This probably isn't a good thing to want to do, but it came up for me,
# so in the spirit of helping others with weird problems (and because this
# seems to be documented almost nowhere):
after_save do
if some_failing_condition
errors.add(:something, "some failure happened.")
raise ActiveRecord::RecordInvalid.new(self)
end
end
@lesliev
Copy link

lesliev commented Jun 6, 2018

THANKS!

@jkeam
Copy link

jkeam commented Apr 15, 2019

Yep, still helpful in 2019 :) Thanks!

@daveharris
Copy link

This approach is also really useful in situations where you want to use ActiveModel::Dirty tracking, but also ensure that it's a valid update before progressing:

user.transaction do
  user.assign_attributes(user_params)
  raise ActiveRecord::RecordInvalid.new(user) if user.invalid?

  if user.email_changed?
    # Do something
  end
end

@dharshan
Copy link

dharshan commented Nov 12, 2019

raises Class: RuboCop::Cop::Style::RaiseArgs cop with rubocop. Any hints?

@blanks88
Copy link

blanks88 commented Aug 6, 2020

Hi!, this is helpfull, but I was wondering how would you rollback the saved record, after that?

@dbrady
Copy link

dbrady commented Oct 16, 2020

Still helpful in October 2020. We were on Rails 6 and we thought "oh, but it's all ActiveRelation now" but nope, ActiveRelation inherits from ActiveRecord::Base, and this is still the correct error class. Thank you!

@mateuszdw
Copy link

raises Class: RuboCop::Cop::Style::RaiseArgs cop with rubocop. Any hints?

raise ActiveRecord::RecordInvalid, user if user.invalid? and no rubocop error

@shimaamarzouk
Copy link

Thanks!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment