Skip to content

Instantly share code, notes, and snippets.

@ise
Last active July 20, 2018 02:37
Show Gist options
  • Save ise/52af35bffcc103e2ab4387b2bf08a291 to your computer and use it in GitHub Desktop.
Save ise/52af35bffcc103e2ab4387b2bf08a291 to your computer and use it in GitHub Desktop.
mongoid callbacks with relation
class A
include Mongoid::Document
field :hoge, type: String
belongs_to :b
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
after_validation on: :create do
p 'after_validation on create'
end
after_validation on: :update do
p 'after_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
class B
include Mongoid::Document
field :fuga, type: String
has_one :a
end
__END__
# mongoid (6.1.1)
> b = B.create(fuga: "b")
> a = A.create(hoge: "a", b: b)
"before_validation"
"before_validation on create"
"after_validation on create"
"before_save on create"
"before_save on update"
"before_create"
> b.fuga = "bb"
> b.save
"before_validation"
"before_validation on update"
"after_validation on update"
@ise
Copy link
Author

ise commented Jul 19, 2018

It is important to note that by default, Mongoid will validate the children of any relation that are loaded into memory via a validates_associated. The relations that this applies to are:
embeds_many
embeds_one
has_many
has_one
has_and_belongs_to_many
https://mongoid.github.io/old/en/mongoid/docs/relations.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment