Right now the following code would produce an error:

class ProductFilter
  include ActiveModel::Validations

  validates :min_price, numericality: { allow_nil: true }
  validates :max_price, numericality: { allow_nil: true, greater_than: 
:min_price }
end

ProductFilter.new(max_price: 100).valid? # => ArgumentError: comparison of 
Integer with nil failed

It's not super obvious what's going on here until digging deep into the 
details how numericality validations work. In order to fix that I have to 
write something like this:

class ProductFilter
  include ActiveModel::Validations

  validates :min_price, numericality: { allow_nil: true }
  validates :max_price, numericality: { allow_nil: true, greater_than: 
->(filter) { filter.min_price.to_i } }
end

ProductFilter.new(max_price: 100).valid? # => true


In my opinion, it would be more helpful to skip these checks, because it 
sounds natural for me that if one field is nil and another should be 
greater then the first one - the second one is valid. I've implemented it 
in the PR https://github.com/rails/rails/pull/34794 - with this change two 
code snippets above work in the exact same way.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-core+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at https://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/d/optout.

Reply via email to