Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
@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

mateuszdw commented Jan 8, 2021

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

shimaamarzouk commented Nov 10, 2021

Thanks!!

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