Created
October 26, 2009 21:42
-
-
Save baroquebobcat/219072 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
# I want to be able to check the validity of the parent object | |
# before saving, and maybe modify it, but I can't use 'before :save' | |
# because those hooks only run if save_parents is true | |
# | |
# I would prefer to not use save_parents because it is part of | |
# the private api, but this seems to be the best solution | |
# I've yet to come across. | |
# | |
require 'rubygems' | |
gem 'dm-core','= 0.10.1' | |
gem 'dm-validations','= 0.10.1' | |
require 'dm-core' | |
require 'dm-validations' | |
DataMapper.setup :default, 'sqlite3::memory:' | |
class Parent | |
include DataMapper::Resource | |
property :id,Serial | |
property :first_name,String,:nullable=>false | |
property :last_name,String,:nullable=>false | |
has n, :children | |
end | |
class Child | |
include DataMapper::Resource | |
property :id,Serial | |
property :first_name,String,:nullable=>false | |
property :last_name,String,:nullable=>false | |
property :suffix,String | |
belongs_to :parent | |
before :save_parents do | |
return if parent && parent.valid? | |
self.parent = Parent.new unless parent | |
if suffix && suffix == "Jr." | |
parent.first_name=first_name | |
end | |
parent.last_name=last_name | |
end | |
end | |
DataMapper.auto_migrate! | |
bill = Child.new :first_name=>'Bill',:last_name=>'William',:suffix=>'Jr.' | |
puts "save successful: #{bill.save}" | |
puts "errors empty?: #{bill.errors.empty?}" | |
puts "parent valid: #{ bill.parent.valid?}" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment