diff --git a/lib/couchrest/mixins/validation.rb b/lib/couchrest/mixins/validation.rb index 4b6e714..e70f4fa 100644 --- a/lib/couchrest/mixins/validation.rb +++ b/lib/couchrest/mixins/validation.rb @@ -115,7 +115,22 @@ module CouchRest # Check if a resource is valid in a given context # def valid?(context = :default) - self.class.validators.execute(context, self) + result = self.class.validators.execute(context, self) + result && validate_casted_arrays + end + + # checking on casted objects + def validate_casted_arrays + result = true + array_casted_properties = self.class.properties.select { |property| property.casted && property.type.instance_of?(Array) } + array_casted_properties.each do |property| + casted_values = self.send(property.name) + next unless casted_values.respond_to?(:each) && casted_values.first.respond_to?(:valid?) + casted_values.each do |value| + result = (result && value.valid?) if value.respond_to?(:valid?) + end + end + result end # Begin a recursive walk of the model checking validity diff --git a/spec/couchrest/more/casted_model_spec.rb b/spec/couchrest/more/casted_model_spec.rb index 4396317..81bd7c2 100644 --- a/spec/couchrest/more/casted_model_spec.rb +++ b/spec/couchrest/more/casted_model_spec.rb @@ -3,6 +3,8 @@ require File.join(File.dirname(__FILE__), '..', '..', 'spec_helper') require File.join(FIXTURE_PATH, 'more', 'card') require File.join(FIXTURE_PATH, 'more', 'cat') +require File.join(FIXTURE_PATH, 'more', 'person') + class WithCastedModelMixin < Hash include CouchRest::CastedModel @@ -122,8 +124,19 @@ describe CouchRest::CastedModel do it "should fail because name is not present" do toy = CatToy.new @cat.toys.push(toy) + @cat.should_not be_valid @cat.save.should be_false end + + it "should not fail if the casted model doesn't have validation" do + Cat.property :masters, :cast_as => ['Person'], :default => [] + Cat.validates_present :name + cat = Cat.new(:name => 'kitty') + cat.should be_valid + cat.masters.push Person.new + cat.should be_valid + end + end end