Skip to content

Instantly share code, notes, and snippets.

@diago
Created April 20, 2011 13:10
Show Gist options
  • Select an option

  • Save diago/931294 to your computer and use it in GitHub Desktop.

Select an option

Save diago/931294 to your computer and use it in GitHub Desktop.
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