Group Related ActiveRecord Validations
Today I learned about the with_options
feature of ActiveRecord. It's used to group validations together in a block. You could use it to transform code like this:
class User < ApplicationRecord
validates :password, length: { minimum: 10 }, if: :is_admin?
validates :email, presence: true, if: :is_admin?
end
Into this:
class User < ApplicationRecord
with_options if: :is_admin? do |admin|
admin.validates :password, length: { minimum: 10 }
admin.validates :email, presence: true
end
end
A use case for this might be a collection of validations that should only be checked when a boolean feature flag like enabled?
is true.