rails - validate product ordered has the available quantity
I have two related validations on separate models. I can validate one way but not another. The post validation works: if I try to change the quantity available as the seller, and people have already ordered some of it, it (correctly) won't let me change the quantity below the amount ordered already.
The order validation does not work: if I try changing the order amount to more than is available, it lets me. It checks only the current sum (I guess before the save), and does not notice the buyer trying to sneak out more than what's available. When I try and change the order back to less than what is available, it won't let me, checking the current sum ordered (before save).
I also tried validating the quantity of the order + the remaining available stock (available -sum ordered), but have the same problem.
How would I get the validation to check what the quantity would be after the save, and then not save it should the value be invalid? It would have to work also for editing an order
class Post < ActiveRecord::Base
belongs_to :product
belongs_to :event
has_many :orders, :d开发者_如何学运维ependent => :destroy
attr_accessible :quantity, :deadline, :product_id, :event_id
validate :quantity_gt_ordered
def quantity_gt_ordered
self.errors.add(:quantity, " - People have already ordered more than this") unless self.quantity >= self.sum_orders
end
def sum_orders
self.orders.sum(:quantity)
end
class Order < ActiveRecord::Base
belongs_to :user
belongs_to :post
attr_accessible :order_price, :post_id, :user_id, :quantity
validate :quantity_is_available
def quantity_is_available
self.errors.add(:quantity, " - Please order only what's available") unless self.sum_post_orders <= self.post.quantity
end
def sum_post_orders
Order.where(:post => self.post).sum(:quantity)
end
You should just be able to compare to the available quantity minus the ordered quantity:
available_quantity = self.post.quantity - self.sum_post_order
if quantity > available_quantity
self.errors.add(:quantity, " - Please order only what's available")
end
And also make sure your sum_post_orders
doesn't include the current order:
Order.where("id != ?", self.id).where(:post => self.post).sum(:quantity)
精彩评论