I'm new to Ruby on Rails and I've been searching how to handle error on Ruby and found this links but none of them works.
redirect_to is not working into rescue block
https://www.ruby-forum.com/t/begin-rescue-not-working/118832/5
Rails 3: Handle ActiveRecord::RecordNotUnique Exception
https://www.honeybadger.io/blog/ruby-exception-vs-standarderror-whats-the-difference/
On my create method I have this
def create
@departments = Spree::Department.new(department_params)
begin
@departments.save
flash[:success] = 'Department Created'
redirect_to admin_departments_path
rescue ActiveRecord::RecordNotUnique => e
flash[:notice] = 'Department name already exists'
redirect_to admin_departments_path
return
end
end
but the problem is it doesn't go to rescue
block so it doesn't render the flash[:notice]
it will render flash[:success]
and redirect in short it will just do the begin
even though it errors out.
Also on @department.save
when I add the !
(bang) if I input a name that is not unique I will get an error Validation failed: Name has already been taken
which I wanted but it won't redirect instead it will go to error screen.
Is there something missing here?