Rails 5 throw abort : how do I setup error messages?
activemodel, ruby-on-rails-5
Solution
You can use `errors.add` for your class method.
User model:
def destroy_validation
if some_condition
errors.add(:base, "can't be destroyed cause x,y or z")
throw(:abort)
end
end
Users controller:
def destroy
if @user.destroy
respond_to do |format|
format.html { redirect_to users_path, notice: ':)' }
format.json { head :no_content }
end
else
respond_to do |format|
format.html { redirect_to users_path, alert: ":( #{@user.errors[:base]}"}
end
end
end
Problem
Rails has introduced this `throw(:abort)` syntax, but now how do I get meaningful destroy errors ? For validation errors one would do ``` if not user.save # => user.errors has information if not user.destroy # => user.errors is empty ``` Here is my model ``` class User before_destroy :destroy_validation, if: :some_reason private def destroy_validation throw(:abort) if some_condition end ```