== ActiveModel::Errors #by_type
Use +#by_type+ on an instance of ActiveModel::Errors (presumably in Rails) to
retrieve a hash of error messages scoped by attribute and type. Empower your
server-sent, serialized form/record validation messages to play nicely with data-binding JS
frameworks. Get more granular with your validation UIs.
==== Installation
Add the following to your +Gemfile+ and +bundle install+.
gem 'ames_by_type'
==== Usage
When an error message is added to an instance of ActiveModel::Errors,
we add said error message (organized by attribute and message type) to a +messages_by_type+
hash. We can retrieve this hash as it exists or with full messages (by keyword argument, shown below).
zebra.errors.add(:name, :blank)
zebra.errors.add(:name, :too_short, count: 2)
zebra.errors.by_type
# => {
name: {
blank: "can't be blank",
too_short: "is too short (minimum is 2 characters)"
}
}
zebra.errors.by_type(full_messages: true)
# => {
name: {
blank: "Name can't be blank",
too_short: "Name is too short (minimum is 2 characters)"
}
}
In a Rails controller action:
...
def create
@zebra = Zebra.new(zebra_params)
if @zebra.save
render json: @zebra
else
render json: @zebra.errors.by_type
end
end
...
Learn how to set up translations for your ActiveRecord models (including error messages)
here[http://guides.rubyonrails.org/i18n.html#translations-for-active-record-models].
==== Copyright
Copyright (c) 2014 Travis Loncar.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.