Skip to content

Conversation

@bmorrall
Copy link
Contributor

@bmorrall bmorrall commented Mar 1, 2020

I looked into Issue #24 to determine why the Errors object was behaving differently from "ActiveSupport::Errors".

From what I've found, Rails will render the Errors using Hash#as_json as implemented by ActiveSupport, instead of Hash#to_json as included with base Ruby.

I wrote a work around that will provide an as_json method when Hash#as_json has been provided by ActiveSupport (i.e. every Rails project), and will raise an error when it is not provided.

I also included some test coverage to ensure to_json works as expected, to avoid any regressions.

@bmorrall bmorrall changed the title Add test coverage for Errors#to_json Make Errors render the same as ActiveModel::Errors Mar 2, 2020
@bmorrall bmorrall force-pushed the to_json_test_coverage branch from b875686 to ef44d26 Compare March 2, 2020 00:15
@bmorrall bmorrall force-pushed the to_json_test_coverage branch from ef44d26 to a5d409d Compare May 18, 2022 05:02
@thlmenezes
Copy link

Looking in active_model/serializers/json.rb there's a root options that I think it could be useful here, because of the recurring pattern of wrapping the json results in a errors key; so the code could be modified to something like

def as_json(options = nil)
  root = if options && options.key?(:root)
    options[:root]
  else
    true
    # could be modified to use an initializer var,
    # like active record has ActiveRecord::Base.include_root_in_json = true
  end

  json = Hash.new.tap do |output|
    raise NotImplementedError.new unless output.respond_to?(:as_json)

    self.each do |field, value|
      output[field] ||= []
      output[field] << value
    end
  end.as_json(options)

  if root
    root = :errors if root == true
    { root => json }
  else
    json
  end
end

with root being a boolean value or a string to be the key of the generated json

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants