Created
April 20, 2011 13:10
-
-
Save diago/931294 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class AcceptableQuantityValidator < ActiveModel::EachValidator | |
| def validate_each(record, attribute, value) | |
| return if value.nil? | |
| order = Order.find(record[:order_id]) | |
| currently_fulfilled = order.total_fulfilled | |
| if record.new_record? | |
| valid_fulfillment = order.quantity - currently_fulfilled | |
| else | |
| valid_fulfillment = order.quantity - (currently_fulfilled - record.quantity_was) | |
| end | |
| record.errors[attribute] << "cannot total more than #{valid_fulfillment}" if value > valid_fulfillment | |
| end | |
| end | |
| class FulfillmentReceived < ActiveModel::Validator | |
| def validate(record) | |
| record.errors[:base] << "Cannot modify a received fulfillment" if record.received_was == true | |
| end | |
| end | |
| class Fulfillment < ActiveRecord::Base | |
| validates_with FulfillmentReceived | |
| attr_accessible :quantity, :ship_date, :tracking_number | |
| belongs_to :order | |
| validates :quantity, :presence => true, | |
| :numericality => {:only_integer => true, :greater_than => 0}, | |
| :acceptable_quantity => true | |
| validates :ship_date, :presence => true, | |
| :format => {:with => /^\d{4}-\d{2}-\d{2}$/} | |
| def received! | |
| return if self.received? | |
| self.received = true | |
| self.save! | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment