Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

Customization options and validation consistency for validates_uniqueness_of using db constraints

#3614

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
  1. 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)

Reported by blythe · December 25th, 2009 @ 04:39 AM

State: stale
Milestone: none
Assigned to: nobody
Importance: Low

Activity

  1. Rohit Arondekar
    Rohit Arondekar
    • State changed from new to stale
    • Importance changed from to Low

    Marking ticket as stale. If this is still an issue please leave a comment with suggested changes, creating a patch with tests, rebasing an existing patch or just confirming the issue on a latest release or master/branches.

    October 8th, 2010 @ 12:31 PM

  2. Rohit Arondekar
    Rohit Arondekar

    Marking ticket as stale. If this is still an issue please leave a comment with suggested changes, creating a patch with tests, rebasing an existing patch or just confirming the issue on a latest release or master/branches.

    October 8th, 2010 @ 12:31 PM