Rails adds beginless range support to clusivity

Now that Ruby 2.7 has added the support for beginless range, Rails 7 also adds support to include the beginless range in ActiveRecord inclusivity/exclusivity validators.

Prior to Rails 7, if we were to add a validation to a Product model where the price needs to be within 5000, we’d have to follow this method-

Before

  class Product < ApplicationRecord

    validates_inclusion_of :price, in: 0..5000

  end

Also, if we would try adding beginless range, then it will throw an error.

  => Product.create(title: "Detergent", description: "A mixture of surfactants with cleansing properties", price: 4000)
  /Users/.rvm/gems/ruby-3.0.2/gems/activemodel-7.0.3/lib/active_model/validations/clusivity.rb:45:in `first': cannot get the first element of beginless range (RangeError)

As it can be seen, it throws an error saying cannot get the first element of beginless range.

After

After Rails 7, we can now add the beginless range.

  class Product < ApplicationRecord

    validates_inclusion_of :price, in: ..5000

  end
  => Product.create(title: "Detergent", description: "A mixture of surfactants with cleansing properties", price: 4000)
  => TRANSACTION (7.5ms)  BEGIN
  Product Create (5.0ms)  INSERT INTO "products" ("name", "description", "created_at", "updated_at", "price") VALUES ($1, $2, $3, $4, $5) RETURNING "id"  [["name", "Detergent"], ["description", "A mixture of surfactants with cleansing properties"], ["created_at", "2022-08-10 20:10:06.227125"], ["updated_at", "2022-08-10 20:10:06.227125"], ["price", 4000]]
  TRANSACTION (2.5ms)  COMMIT                                                                                      

Check out the PR for more details.

Need help on your Ruby on Rails or React project?

Join Our Newsletter