Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # City:
- # Custom Validation on external_id field which should be unique within customer
- # name & state should be present for every record of city
- class City < ActiveRecord::Base
- include ValidationHelper
- belongs_to :state
- belongs_to :customer
- validates_presence_of :name, :state
- validate -> { unique_prop_in_assoc('external_id', 'customer') if external_id }
- end
- # Includes utility methods to apply validations on models
- module ValidationHelper
- def unique_prop_in_assoc(prop, assoc)
- assoc_obj_id = method(assoc).call ? method(assoc).call.id : nil
- objects = self.class.where(prop.to_sym => method(prop).call,
- "#{assoc}_id" => assoc_obj_id).where.not(id: self.id)
- if objects.count > 0 && objects[0].has_attribute?(:is_deleted)
- objects = objects.where.not(is_deleted: true)
- end
- if objects.count > 0
- errors.add prop.to_sym, "of #{self.class.name} should be
- unique within #{assoc}"
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement