This patch extends #3486
to be consistent with standard AR validations and support
customized error message. #3486 patches ActiveRecord to convert
db-generated errors for unique constraint violations into active
record error messages.
This patch addresses some of those concerns and extends that
functionality to:
1. Add hooks through validates_uniqueness_of to support customized
error messages
# These two are equivalent functions: lazy option skips standard proactive validation query
validates_uniqueness_of :name, :message => 'already used!", :lazy => true
handle_unique_key_violation :name, :message => 'already used!"
# Extend the functionality to all AR objects
ActiveRecord::Base.handle_unique_key_violations
- Keep save! consistent with standard validation
functionality
The current implementation does not add errors for save! and raises
RecordNotUnique instead of RecordInvalid exceptions.
- Add error messages to the AR instance as with standard
validations. The following functionality would no longer work since
no error messages are populated
begin
record.save!
rescue => e
flash[:error] = record.errors.full_messages.first
redirect_to :blah_url
end
- Raise a RecordInvalid subclassed exception for explicitly
declared validations. Convenient for rescues_from functionality
that looks for RecordInvalid
The patch always adds error messages for save and save!, but
only raises RecordInvalid when validates_uniqueness_of is
explicitly declared. Conversion of RecordNotUnique to AR errors is
exposed in add_record_not_unique_errors to support for further
customization (when explicitly handling RecordNotUnique).
The attached patches are based on current (and include #3486)