Skip to content

Conversation

notapatch
Copy link
Contributor

Section: Validate quantity of products

The book code listing for the validator causes a warning in Rails 6.1. The suggested warning fix, method add, has worked since Rails 3.

app/validators/enough_products_validator.rb
class EnoughProductsValidator < ActiveModel::Validator
  def validate(record)
    record.placements.each do |placement|
      product = placement.product
      if placement.quantity > product.quantity
        # ****************************** << deprecated in 6.1 ********************
        record.errors[product.title.to_s] << "Is out of stock, just #{product.quantity} left"    
      end
    end
  end
end

This generates the following warning:

DEPRECATION WARNING: Calling `<<` to an ActiveModel::Errors message array in order to add an error is deprecated. 
Please call `ActiveModel::Errors#add` instead. 
(called from block in validate at ... market_place_api/app/validators/enough_products_validator.rb:6)

You can fix this by changing errors method << to add. Add has been available since 3.0 and is the suggested change in 6.1 so this change works with the current code and future proofs the book.

record.errors.add product.title,  "Is out of stock, just #{product.quantity} left"

@notapatch notapatch force-pushed the pr-ch08-fix-validate-quantity-of-products-warning branch from a31a77c to 71ce55e Compare January 23, 2021 16:46
@madeindjs
Copy link
Owner

Great! Thank you for correct this warning 👍

@madeindjs madeindjs merged commit a51b34a into madeindjs:master Jan 24, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants