Created
February 19, 2011 17:57
-
-
Save TMaYaD/835223 to your computer and use it in GitHub Desktop.
nested attributes with validate parent
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
#app/models/parent.rb | |
class Parent < ActiveRecord::Base | |
accepts_nested_attributes_for :children | |
validate :children_are_less_than_two | |
private | |
def children_are_less_than_two | |
errors.add(:base, | |
"shouldn't have more than two children" | |
) if children.count > 2 | |
end | |
end | |
#app/models/child.rb | |
class Child < ActiveRecord::Base | |
belongs_to :parent | |
end | |
#spec/models/parent_spec.rb | |
describe Parent do | |
it "should accept nested attributes for children and validate parent before saving a child" do | |
parent = Parent.new(children_attributes => { | |
0 => {}, | |
1 => {}, | |
}).save.should be true | |
Child.new(:parent => parent).save.should be false | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment