Skip to content

Instantly share code, notes, and snippets.

@Hampei
Created October 27, 2016 17:19
Show Gist options
  • Save Hampei/b612670245c5cb9c9b8fac3d8382635d to your computer and use it in GitHub Desktop.
Save Hampei/b612670245c5cb9c9b8fac3d8382635d to your computer and use it in GitHub Desktop.
# 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"]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment