From 01ad4bedc6be3691907205edbed6b8827aeab799 Mon Sep 17 00:00:00 2001 From: Ryan Hall Date: Thu, 29 Nov 2018 11:30:00 -0600 Subject: [PATCH] Fix error when validations fail on nested attributes (#67) * Fix error when validations fail on nested attributes. * Add spec for nested attributes validation bugfix --- lib/stitches/errors.rb | 2 +- spec/errors_spec.rb | 9 ++++++++- 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/lib/stitches/errors.rb b/lib/stitches/errors.rb index 7abbd35..43f110b 100644 --- a/lib/stitches/errors.rb +++ b/lib/stitches/errors.rb @@ -70,7 +70,7 @@ def self.from_exception(exception) def self.from_active_record_object(object) errors = object.errors.to_hash.map { |field,errors| code = "#{field}_invalid".parameterize - message = if object.send(field).respond_to?(:errors) + message = if object.respond_to?(field) && object.send(field).respond_to?(:errors) object.send(field).errors.full_messages.sort.join(', ') else object.errors.full_messages_for(field).sort.join(', ') diff --git a/spec/errors_spec.rb b/spec/errors_spec.rb index b9304b5..78a7f01 100644 --- a/spec/errors_spec.rb +++ b/spec/errors_spec.rb @@ -94,6 +94,13 @@ class FakePerson expect(errors_hash[1]["code"]).to eq("person_invalid") expect(errors_hash[1]["message"]).to eq("Age is not a number, First name can't be blank, Last name starts with z.") end + + it "works with nested attributes" do + object.errors.add("something.nested", "is required") + errors = Stitches::Errors.from_active_record_object(object) + errors_hash = JSON.parse(errors.to_json).sort_by {|_| _["code"] } + expect(errors_hash[0]["code"]).to eq("something-nested_invalid") + expect(errors_hash[0]["message"]).to eq("Something nested is required") + end end end -