Advertisement
Guest User

Untitled

a guest
May 26th, 2015
209
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.94 KB | None | 0 0
  1. # City:
  2. # Custom Validation on external_id field which should be unique within customer
  3. # name & state should be present for every record of city
  4. class City < ActiveRecord::Base
  5. include ValidationHelper
  6. belongs_to :state
  7. belongs_to :customer
  8. validates_presence_of :name, :state
  9. validate -> { unique_prop_in_assoc('external_id', 'customer') if external_id }
  10. end
  11.  
  12. # Includes utility methods to apply validations on models
  13. module ValidationHelper
  14. def unique_prop_in_assoc(prop, assoc)
  15. assoc_obj_id = method(assoc).call ? method(assoc).call.id : nil
  16. objects = self.class.where(prop.to_sym => method(prop).call,
  17. "#{assoc}_id" => assoc_obj_id).where.not(id: self.id)
  18. if objects.count > 0 && objects[0].has_attribute?(:is_deleted)
  19. objects = objects.where.not(is_deleted: true)
  20. end
  21. if objects.count > 0
  22. errors.add prop.to_sym, "of #{self.class.name} should be
  23. unique within #{assoc}"
  24. end
  25. end
  26. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement