ruby-on-railsvalidates-uniqueness-of

Rails - Custom validation of uniqueness


I want to impart uniqueness on a column (type string), however the problem is on some of the strings I'm truncating part of the beginning before inserting them into the database using a function and before_save. Thus the rails uniqueness validation doesn't work since the input might be different from what's in the database, even though after the truncation/formatting, they should be the same.

I want to be able to truncate my string first, then validate it's uniqueness, however I'm not sure if it's possible using the rails validates uniqueness: true. Will I just have to write a custom validate?


Solution

  • The order of Rails callback is:

    (-) save

    (-) valid

    (1) before_validation

    (-) validate

    (2) after_validation

    (3) before_save

    (4) before_create

    (-) create

    (5) after_create

    (6) after_save

    (7) after_commit

    The detail is here. So you just simply do something like:

    validates :your_data_field, uniqueness: true
    before_validation :normalize_data
    
    def normalize_data
      # Normalize your data here
    end
    

    So it will work exactly as you described, and don't need to write and custom validation. It will be more beautiful!