简体   繁体   中英

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 ?

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!

As you mentioned, you'll want to create a custom validator and use validates_with. Information about that is here:

http://apidock.com/rails/ActiveModel/Validations/ClassMethods/validates_with

To follow DRY principles, and also to ensure any changes to your truncation logic are reflected in both your validator and your before_save callback, I suggest creating a method that returns the truncated string, and use that same method within the validator and the callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM