A simple Rails helper which displays a HTML div with the validation errors attached to a model.
Model Error Messages's installation is pretty standard, add the following line to your Gemfile
, then run bundle install
:
gem 'model_error_messages'
This gem allows you to use a helper called model_error_messages
.
By default, the wrapper div
has the Bootstrap-friendly classes alert alert-danger
.
If you have a typical form, you would want to display model_error_messages(@model)
next to it, which will render something like:
<div class="alert alert-danger article-error-messages">
<ul>
<li>Title can't be blank</li>
<li>You must select an author</li>
</ul>
</div>
... or if there is only one error:
<div class="alert alert-danger article-error-messages">
<p>Title can't be blank</p>
</div>
Example of integration:
<%= model_error_messages(@article) %>
<%= form_for @article do |f| %>
<!-- ... form fields ... -->
<% end %>
- Include any other dependencies
- Influence the generation of errors
- Inject or execute any code in your controllers and models
- Do anything with the
flash
messages - Anything not listed in "What this gem does"
You can change the default behavior of model_error_messages
by:
Create a file config/initializers/model_error_messages.rb
and replace one of the defaults:
ModelErrorMessages.configure do |config|
# Multiple errors will rendered in a several <li> in a <ul>, while one error will be rendered in a <p>
config.single_error_in_paragraph = true
# The following classes will be added in the main wrapper div.
config.classes = lambda do |model|
[
'alert',
'alert-danger',
model.class.model_name.param_key + '-error-messages'
].join(' ')
end
# Note: you can pass a simple string to `config.classes`, example:
# config.classes = 'alert alert-danger'
# HTML that will be added before the list of errors.
config.prepend_html = String.new
# HTML that will be added after the list of errors.
config.append_html = String.new
end
Examples:
<%= model_error_messages(@article, single_error_in_paragraph: false) %>
Don't hesitate to send a pull request!
$ bundle install
$ bundle exec rspec spec/
This software is distributed under the MIT License. Copyright (c) 2016-2019, Christophe Maximin