Skip to content

Conversation

@opsys-saito
Copy link

Motivation / Background

The :in option of numericality currently only accepts a static Range,
while other numericality options such as :greater_than and
:less_than_or_equal_to already support procs and symbols.

In practice, it is common for the valid range of a numeric attribute to depend
on other attributes of the same record. For example, a Product model may
define a minimum and maximum allowed price:

class Product < ApplicationRecord
  # columns: price, min_price, max_price
end

Validating that price falls between min_price and max_price currently
requires a custom validate method, even though the intent fits naturally
within numericality.

Allowing :in to accept a proc or symbol that resolves to a Range enables
this use case to be expressed declaratively:

validates :price, numericality: { in: ->(p) { p.min_price..p.max_price } }

This change brings the :in option in line with other numericality options and
with validators such as inclusion and exclusion, while remaining fully
backward compatible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant