On Tue, Sep 25, 2012 at 06:39:58AM -0700, Szymon Nowak wrote:
> There are few issues with the current ActiveModel::Errors class.
> 
> Firstly, when an error is added to ActiveModel::Errors class via #add 
> method 
> (https://github.com/rails/rails/blob/master/activemodel/lib/active_model/errors.rb#L294)
>  
> its translation is added. It should not be translated when being added, but 
> only when being read.
> 
> The second issue is a bit bigger. We'd like to create error responses in 
> our API similar to GitHub: 
> 
> {
>    "message": "Validation Failed",
>    "errors": [
>      {
>        "resource": "Issue",
>        "field": "title",
>        "code": "missing_field"
>      }
>    ]
>  }
> 
> 
> Currently it's impossible to figure out which validations actually failed 
> for a given field, as AM::Errors provides only field name and translated 
> error message. We've got a simple workaround for this issue:
> 
> module ActiveModel
>   class Errors
>     def error_types
>       @_error_types ||= Hash.new{|hash,k| hash[k] = []}
>     end
> 
>     def add_with_save_names(attribute, message = nil, options = {})
>       message ||= :invalid
>       message = message.call if message.is_a?(Proc)
>       error_types[attribute] << message
>       add_without_save_names(attribute, message, options)
>     end
> 
>     alias_method_chain :add, :save_names
>   end
> end 
> 
> 
> This solution is far from perfect, but it's relatively simple and so far 
> works for us.
> 
> The best solution would be to actually build a structure similar to GitHub 
> response - from that structure it would be trivial to build #full_messages 
> and similar methods and it would provide a lot of additional info which 
> would be extremely useful for creating APIs.

Seems good.  Can you work on a patch and send a PR?  If we can maintain
backwards compat, I am happy.

-- 
Aaron Patterson
http://tenderlovemaking.com/

Attachment: pgpTAKUDCfdpS.pgp
Description: PGP signature

Reply via email to