A thread was created here, but it doesn\'t solve my problem.
My code is:
course.rb
class Course < ApplicationRecord
COU
UPDATED to support .valid?
to have idempotent validations.
This solution isn't really elegant, but it works.
We had this problem in an API application. We do not like the idea of rescue
ing this error every time it is needed to be used in any controller or action. So we rescue
d it in the model-side as follows:
class Course < ApplicationRecord
validate :course_type_should_be_valid
def course_type=(value)
super value
@course_type_backup = nil
rescue ArgumentError => exception
error_message = 'is not a valid course_type'
if exception.message.include? error_message
@course_type_backup = value
self[:course_type] = nil
else
raise
end
end
private
def course_type_should_be_valid
if @course_type_backup
self.course_type ||= @course_type_backup
error_message = 'is not a valid course_type'
errors.add(:course_type, error_message)
end
end
end
Arguably, the rails-team's choice of raising ArgumentError
instead of validation error is correct in the sense that we have full control over what options a user can select from a radio buttons group, or can select over a select
field, so if a programmer happens to add a new radio button that has a typo for its value, then it is good to raise an error as it is an application error, and not a user error.
However, for APIs, this will not work because we do not have any control anymore on what values get sent to the server.