Search code examples
ruby-on-railsjsonvalidationactivemodel

Rails validation messages as JSON for accepts_nested_attributes_for models


I have a Mongoid model which has several nested sub models and collections. I set the attributes from my controller for those models using the Rails accepts_nested_attributes_for functionality.

When validation fails on the parent model, #errors only contains error messages from the parent model, not any of the sub models.

This is not normally a problem as each nested model's error messages would normally be read when the form was re-rendered using the regular Rails form helpers. However, I want all the errors in one JSON object for consumption by a Backbone app.

At the moment, I am iterating through all the nested models and manually munging all the error collections together, which is tedious, but works.

Am I missing something? Is there an easier way?


Solution

  • I come across the same problem useing Angular.js with rails... I think there is no better way to get around this without iterating through all the errors in the nested models. This monkeypatch is my current sollution that only works for one to one relations:

    module ActionController
      class Responder
        def json_resource_errors
          def get_error_recursively_from(res)
            Hash[res.errors.map do |key, value|
              if res.send(key).is_a? Mongoid::Relations
                result = get_error_recursively(res.send(key))
              else
                result = value
              end
              [key, result]
            end]
          end
    
          { :errors => get_error_recursively_from(resource) }
        end
      end
    end