loading...

TIL: newer uniqueness validation syntax

tamouse profile image Tamara Temple ・1 min read

Today, I learned how to write a rails uniqueness validation using the validates method.


In Rails versions prior to 5, the standard accepted way to do a scoped uniqueness validation was by using the validate_uniqueness_of method:

class Subcategory < ApplicationRecord

  belongs_to :category

  validate_presence of :slug
  validate_uniqueness_of :slug, scope: :category_id
end
Enter fullscreen mode Exit fullscreen mode

With Rails 5 (I'm not sure exactly when) the longer forms are being deprecated in favour of using the validates method instead.

In the api docs, however, the uniqueness validator isn't discussed, not even as an example.

I went digging into the code to try and figure it out and didn't make much headway with that.

Luckily, I had rubocop set up to complain about the use of the older methods, and told it to fix the failures it found.

The acceptable syntax is:

class Subcategory < ApplicationRecord

  belongs_to :category

  validates :slug, presence: true
  validates :slug, uniqueness: { scope: :category_id }
end
Enter fullscreen mode Exit fullscreen mode

Now to update my snippets! :)

Discussion

pic
Editor guide
Collapse
jennapederson profile image
Jenna Pederson

Nice! I didn’t realize the old way was being deprecated.