1

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?

acqwctm
  • 27
  • 5

2 Answers2

2

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!

Hieu Pham
  • 6,577
  • 2
  • 30
  • 50
1

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.

Brian
  • 4,921
  • 3
  • 20
  • 29