Search code examples
performanceactiverecordprocessing-efficiencyvalidates-uniqueness-of

Efficiency of uniqueness validation in Active Record Rails


Which is more efficient while creating records with unique values for a column in rails Placing uniqueness validation vs finding if record exists with same value and create based on the existence.

Which is more efficient in terms of coding and performance.


Solution

  • A database uniqueness constraint will give you the highest performance.

    At the application level, whether you are using validates_uniqueness_of or manually finding if the record exists, the performance will basically be the same. In fact, that is exactly how it is implemented in Rails: https://github.com/rails/rails/blob/0d73d6e7b6dd1900f105397460b777ef6c03d3b6/activerecord/lib/active_record/validations/uniqueness.rb#L33