Skip to content

Instantly share code, notes, and snippets.

@ise
Created July 17, 2018 09:25
Show Gist options
  • Save ise/4ba3175cb47271f21eb2d3a10741a66a to your computer and use it in GitHub Desktop.
Save ise/4ba3175cb47271f21eb2d3a10741a66a to your computer and use it in GitHub Desktop.
mongoid callbacks
class A
include Mongoid::Document
field :hoge, type: String
before_validation do
p 'before_validation'
end
before_validation on: :create do
p 'before_validation on create'
end
before_validation on: :update do
p 'before_validation on update'
end
before_create do
p 'before_create'
end
before_update do
p 'before_update'
end
before_save on: :create do
p 'before_save on create'
end
before_save on: :update do
p 'before_save on update'
end
end
__END__
# mongoid (6.1.1)
> a = A.new
> a.hoge = 'aaa'
> a.save
"before_validation"
"before_validation on create"
"before_save on create"
"before_save on update"
"before_create"
> A.create(hoge: 'aaa')
"before_validation"
"before_validation on create"
"before_save on create"
"before_save on update"
"before_create"
> a = A.first
> a.hoge = 'bbb'
> a.save
"before_validation"
"before_validation on update"
"before_save on create"
"before_save on update"
"before_update"
> a = A.first
> a.update(hoge: 'bbb')
"before_validation"
"before_validation on update"
"before_save on create"
"before_save on update"
"before_update"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment