Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baroquebobcat/205496 to your computer and use it in GitHub Desktop.
Save baroquebobcat/205496 to your computer and use it in GitHub Desktop.
=begin
I was trying to setup some behavior where if
a new object's parent was not saved, I could
communicate the errors to the user using the standard model.errors stuff
and ran into a problem.
'before :save' does not run before :save, it runs before save_self
since save looks like this:
chainable do
def save
save_parents && save_self && save_children
end
end
if the parent objects fail to save, then the before :save
and by extension before :valid? calls are never made.
=end
require 'rubygems'
require 'dm-core'
require 'dm-validations'
DataMapper.setup(:default,"mysql://root@localhost/testing")
class A
include DataMapper::Resource
property :id,Serial
belongs_to :b
before :save do
puts 'before save'
end
after :save_parents do
puts 'after save parents'
if b.errors
b.errors.each do |error|
p error.to_s
errors.add :b,error.to_s
end
end
end
before :valid? do
puts 'before valid'
end
end
class B
include DataMapper::Resource
has 1, :a
property :id,Serial
property :x,String
validates_present :x
end
DataMapper.auto_migrate!
a = A.new
a.b = B.new
p a.save
p a.errors.on :b
#$ ruby dm_before_valid.rb
#
#after save parents
#false
#[]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment