Advertisement
Guest User

Untitled

a guest
Oct 28th, 2016
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.38 KB | None | 0 0
  1. # default context :create when new, :update when persisted.
  2. # Since rails 4.2 you can define add multipe contexts per validation
  3. # Since rails 5.0 you can specify multiple context when saving/validating.
  4.  
  5. class Invoice < ApplicationRecord
  6. validate :check_remote, on: [:create, :remote]
  7. validate :check_total, on: [:create]
  8. validate :foo, on: :remote
  9.  
  10. def check_remote
  11. errors.add :base, 'remote not right'
  12. end
  13.  
  14. def check_total
  15. errors.add :total, 'total not right'
  16. end
  17.  
  18. def foo
  19. errors.add :base, 'bar not right'
  20. end
  21. end
  22.  
  23. invoice = Invoice.new
  24. invoice.save # ["remote not right", "Total total not right"]
  25. # specifying a context overwrites the default context.
  26. invoice.save context: :remote # ["remote not right", "bar not right"]
  27. # so add it in when needed.
  28. invoice.save context: [:remote, :create] # ["remote not right", "bar not right", "Total total not right"]
  29.  
  30. # valid works the save as save.
  31. invoice.valid? # ["remote not right", "Total total not right"]
  32. invoice.valid? :remote # ["remote not right", "bar not right"]
  33. invoice.valid? [:remote, :create] # ["remote not right", "bar not right", "Total total not right"]
  34.  
  35. invoice = Invoice.last
  36. invoice.save # correct, since we're doing nothing on: :update
  37. invoice.save context: :remote # ["remote not right", "bar not right"]
  38. invoice.valid? [:create, :remote] # ["remote not right", "bar not right", "Total total not right"]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement