On Tuesday, 25 September 2012 19:26:40 UTC+2, Aaron Patterson wrote: > 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. >
I'll make all current methods to return the same result as they do now (even #to_json and similar methods) and use new structure only internally. The only question is how this new structure should be accessed via ActiveModel object - object.errors.errors? :) BTW. Aaron, if you have a while could you check PR about ActionDispatch::ParamsParser (https://github.com/rails/rails/pull/7444)? -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Core" group. To view this discussion on the web visit https://groups.google.com/d/msg/rubyonrails-core/-/KCbo-mA3STgJ. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at http://groups.google.com/group/rubyonrails-core?hl=en.
