Skip to content

Commit

Permalink
Fix error when validations fail on nested attributes (#67)
Browse files Browse the repository at this point in the history
* Fix error when validations fail on nested attributes.

* Add spec for nested attributes validation bugfix
  • Loading branch information
halloffame authored Nov 29, 2018
1 parent 67a4448 commit 01ad4be
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/stitches/errors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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(', ')
Expand Down
9 changes: 8 additions & 1 deletion spec/errors_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit 01ad4be

Please sign in to comment.