Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
require 'rubygems'
require 'dm-core'
require 'dm-migrations'
require 'dm-validations'
class Pet
include DataMapper::Resource
belongs_to :human
property :id, Serial
property :name, String, :required => true
property :type, Discriminator
end
class Human
include DataMapper::Resource
has n, :pets
property :id, Serial
property :name, String
end
class Dog < Pet
end
DataMapper.setup(:default, "sqlite3::memory:")
DataMapper.auto_migrate!
DataMapper.finalize
pet = Pet.new
puts pet.valid? # => false
puts pet.errors.inspect # => #<DataMapper::Validations::ValidationErrors:0x10127de48 @errors=#<OrderedHash {:human_id=>["Human must not be blank"], :name=>["Name must not be blank"]}>, @resource=#<Pet @id=nil @name=nil @type=Pet @human_id=nil>>
pet = Pet.new(:name => "timmy")
puts pet.valid? # => false
puts pet.errors.inspect # => #<DataMapper::Validations::ValidationErrors:0x101172558 @errors=#<OrderedHash {:human_id=>["Human must not be blank"]}>, @resource=#<Pet @id=nil @name="timmy" @type=Pet @human_id=nil>>
pet = Pet.new(:name => "timmy", :human => Human.create(:name => "noddy"))
puts pet.valid? # => true
dog = Dog.new
puts dog.valid? # => false
puts dog.errors.inspect # => #<DataMapper::Validations::ValidationErrors:0x1043c7fd0 @errors=#<OrderedHash {:name=>["Name must not be blank"]}>, @resource=#<Dog @id=nil @name=nil @type=Dog @human_id=nil>>
dog = Dog.new(:name => "spot")
puts dog.valid? # => true
puts dog.errors.inspect # => #<DataMapper::Validations::ValidationErrors:0x1044f0308 @errors=#<OrderedHash {}>, @resource=#<Dog @id=nil @name="spot" @type=Dog @human_id=nil>>
puts dog.save # => false
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment