Skip to content

Instantly share code, notes, and snippets.

@TMaYaD
Created February 19, 2011 17:57
Show Gist options
  • Save TMaYaD/835223 to your computer and use it in GitHub Desktop.
Save TMaYaD/835223 to your computer and use it in GitHub Desktop.
nested attributes with validate parent
#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