You can use the before_validation
callback to check validity yourself, and when it fails, trigger the behavior you're looking for. So, one way to do it would be to write code in before_validation
, and in there you could do a simple .valid?
call, or manually run the validation for uniqueness by itself. When validation fails, you can stop the callback chain, and trigger custom behavior.
before_validation
is one of the many ActiveRecord callbacks available to you.
Another, more common way to do it would be, in your controller, instead of just saving you can basically wrap the .save
call in an if statement, because .save
returns false
if validation fails. You can use this as a way to redirect to an alternate action, in the situation you describe.
@new_record = ThingImSaving.new(params[:thing_im_saving]
if @new_record.save
...validation has passed, continue the normal path
else
...validation has failed, do something else.
end