Search code examples
ruby-on-railsvalidationbelongs-to

Rails - Can parent models validate attribute values of the models that belong to them?


In my app I have the following relationships:

  • An order has many order_items
  • An order_item has one product
  • An order_item has a property for quantity (How much is the user ordering?)
  • And finally a product has a property stock (How much is left?)

Before submitting the order, I want to make sure that there is enough stock to fulfill the order quantity but I'm not sure where I should be doing this validation.

At the moment I have a before update action which checks stock levels before the update action:

def check_stock
  check_results = @order.order_items.collect do |item| 
    if (item.product.stock < item.quantity)
      flash.now[:danger] = "Sorry, it looks like we're out of some of those things"
      false
    else
      true
    end
  end

   if check_results.include?(false)
      render "show"
      return false
   else 
      @order.order_items.each do |item|
          item.remove_stock          
      end
    end
end

It does it's job and blocks the update action, but it's not very elegant. Does anyone know of a better way? It feels like there should be a way to validate the quantity value of the order_item by manipulating the form... but yeah, not really sure how to go about it.


Solution

  • Take a look at 2.2 validates_associated explained on http://guides.rubyonrails.org/active_record_validations.html

    A rough idea is something like this

    You would move the item.product.stock < item.quantity to your order_item.rb under a function something like validate_stock and change it to item.product.stock >= item.quantity. Then add validate :validate_stock to order_item.rb

    Then add validates_associated :order_items in your order.rb