Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # default context :create when new, :update when persisted.
- # Since rails 4.2 you can define add multipe contexts per validation
- # Since rails 5.0 you can specify multiple context when saving/validating.
- class Invoice < ApplicationRecord
- validate :check_remote, on: [:create, :remote]
- validate :check_total, on: [:create]
- validate :foo, on: :remote
- def check_remote
- errors.add :base, 'remote not right'
- end
- def check_total
- errors.add :total, 'total not right'
- end
- def foo
- errors.add :base, 'bar not right'
- end
- end
- invoice = Invoice.new
- invoice.save # ["remote not right", "Total total not right"]
- # specifying a context overwrites the default context.
- invoice.save context: :remote # ["remote not right", "bar not right"]
- # so add it in when needed.
- invoice.save context: [:remote, :create] # ["remote not right", "bar not right", "Total total not right"]
- # valid works the save as save.
- invoice.valid? # ["remote not right", "Total total not right"]
- invoice.valid? :remote # ["remote not right", "bar not right"]
- invoice.valid? [:remote, :create] # ["remote not right", "bar not right", "Total total not right"]
- invoice = Invoice.last
- invoice.save # correct, since we're doing nothing on: :update
- invoice.save context: :remote # ["remote not right", "bar not right"]
- invoice.valid? [:create, :remote] # ["remote not right", "bar not right", "Total total not right"]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement