Created
October 8, 2009 22:53
-
-
Save baroquebobcat/205496 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=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