Created
January 7, 2010 16:21
-
-
Save baroquebobcat/271337 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| require 'rubygems' | |
| #gem 'dm-core','= 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 :valid?, :set_jrs_parent | |
| def set_jrs_parent | |
| return if parent && parent.valid? | |
| parent = Parent.new unless parent | |
| if suffix && suffix == "Jr." | |
| parent.first_name=first_name | |
| end | |
| parent.last_name=last_name | |
| parent.save | |
| self.parent = parent | |
| end | |
| end | |
| DataMapper.auto_migrate! | |
| bill = Child.new :first_name=>'Bill',:last_name=>'William',:suffix=>'Jr.' | |
| bill.parent = Parent.new | |
| puts "save successful: #{bill.save}" | |
| puts "errors empty?: #{bill.errors.empty?}" | |
| puts "parent valid: #{ bill.parent.valid?}" | |
| bill.set_jrs_parent | |
| puts "save after fix?: #{bill.save}" | |
| #---Output-------------- | |
| # save successful: false | |
| # errors empty?: true | |
| # parent valid: false | |
| # save after fix?: true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment