Created
October 12, 2010 10:10
-
-
Save solnic/621977 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
| #!/usr/bin/env ruby | |
| # | |
| # encoding: utf-8 | |
| require 'dm-sqlite-adapter' | |
| require 'dm-migrations' | |
| require 'dm-validations' | |
| DataMapper.setup :default, "sqlite::memory:" | |
| class Group | |
| include DataMapper::Resource | |
| property :id, Serial | |
| property :name, String, :length => 10..100 | |
| has n, :students | |
| end | |
| class Student | |
| include DataMapper::Resource | |
| property :id, Serial | |
| property :name, String, :required => true | |
| belongs_to :group | |
| has n, :scores | |
| def _save | |
| result = super | |
| unless result | |
| validate if dirty_self? | |
| validate_parents if dirty_parents? | |
| validate_children if dirty_children? | |
| end | |
| result | |
| end | |
| def validate | |
| valid? | |
| end | |
| def validate_parents | |
| parent_relationships.each do |relationship| | |
| parent = relationship.get(self) | |
| unless parent.valid? | |
| errors[relationship.name] = parent.errors | |
| end | |
| end | |
| end | |
| def validate_children | |
| child_associations.each do |collection| | |
| if collection.dirty? | |
| collection.each do |child| | |
| unless child.valid? | |
| (errors[collection.relationship.name] ||= []) << child.errors | |
| end | |
| end | |
| end | |
| end | |
| end | |
| end | |
| class Score | |
| include DataMapper::Resource | |
| property :id, Serial | |
| property :result, String, :length => 1..2 | |
| belongs_to :student | |
| end | |
| DataMapper.finalize | |
| DataMapper.auto_migrate! | |
| group = Group.new :name => 'foo' | |
| student = Student.new :group => group | |
| student.scores.new :result => 'A' | |
| student.scores.new :result => '' | |
| student.save | |
| puts student.errors.inspect | |
| puts "*"*80 | |
| puts student.errors[:group].inspect | |
| puts "*"*80 | |
| puts student.errors[:scores].inspect |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment