vendredi 23 juin 2017

Validation is not working if integer value of old attribute is same as that of new attribute

I've a model Cart having has_many relationship with cart_items.

# cart.rb:
  accepts_nested_attributes_for :cart_items, allow_destroy: true
  has_many :cart_items, dependent: :destroy, inverse_of: :cart

# cart_item.rb:
  validates :quantity, presence: true, numericality: { greater_than: 0 }

# Controller code:

  def update
    current_cart.assign_attributes(params[:cart])
    .....
    current_cart.valid?
  end

While updating cart_items, if integer (to_i) value of quantity is same as old value then validation is not working.

For example, If old value of quantity is 4, now new value is updated to 4abc then quantity validation is not working and record is considered as valid.

Although, if new value is updated from 4 to 5abc then it shows a validation error, as expected.

Any suggestions why this all is happening?

EDIT:

Here's the output of rails console:

[3] pry(#<Shopping::CartsController>)> cart
=> #<Cart id: 12, created_at: "2017-06-22 13:52:59", updated_at: "2017-06-23 08:54:27">

[4] pry(#<Shopping::CartsController>)> cart.cart_items
[#<CartItem id: 34201, cart_id: 12, quantity: 4, created_at: "2017-06-23 05:25:39", updated_at: "2017-06-23 08:54:27">]

[5] pry(#<Shopping::CartsController>)> param_hash
=> {"cart_items_attributes"=>{"0"=>{"id"=>"34201", "quantity"=>"4abc"}}}
[6] pry(#<Shopping::CartsController>)> cart.assign_attributes param_hash
=> nil
[7] pry(#<Shopping::CartsController>)> cart.valid?
=> true

Here, previous quantity of cart_item is 4 and new value is 4abc, but still the cart is validated.

Aucun commentaire:

Enregistrer un commentaire