I needed an error object to pass errors between controllers and js views for ajax responses. I wanted to use ActiveModel::Errors since then I could easily merge errors from model validation to non-model errors. But Ive been having some problems using this approach.
Using ActiveModel::Errors.new(nil)
If I try and call to_a() like so:
@errors = ActiveModel::Errors.new(nil)
@errors[:test] = "is a required field."
@errors.to_a().join("<br />")
I get the error:
undefined method `human_attribute_name' for NilClass:Class
Its trying to call the human_attribute_name for the nil I passed into Errors.new which is suppose to be a ActiveRecord Model.
I am wondering if anyone knows of a better way to handle errors or if the approach I am taken has already been made into some gem.
Chances are your validations are related to “something” that could be encapsulated in a model – it just doesn’t need to be an ActiveRecord model.
You can use validations in any plain ruby object by doing something like this:
Then, the usual suspects would work just fine: