Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove prepended attribute name from full error messages for errors[:base]

We're creating a Rails form that uses the dynamic_form gem to display error messages. For one of the models the form interacts with, we created a custom validator:

class Contact < ActiveRecord::Base
  belongs_to :agency

  validate :new_signups_have_contact_information

  def new_signups_have_contact_information
    if agency && agency.is_new_signup?
      unless (email && email != '') || (phone && phone != '')
        errors[:base] << "Please include a phone number or email."
      end
    end
  end
end

So far, so good. When we display these errors our view, though:

<%= form_for @contact do |contact_form| %>
  <%= contact_form.error_messages %>
  <%# snip %>
<% end %> 

We get this message in the errors that are generated when the validation fails:

Contacts base Please include a phone number or email.

How can we remove the prepended "Contacts base" from the generated error string?


We've done some research: We know that this is happening because, by default, Rails' error message system automatically prepends attribute names to their error strings. In addition, in most cases, we can modify the English localization file to remove the prepended strings.

The official Rails guide to do so, however, does not list how to change the localization for error messages given to the errors[:base] array or generated using custom validations. It lists how to override the generated strings for all of the built-in validations, but no other errors.

So, one approach we'd be willing to use: How do we configure config/locales/en.yml to remove the prepended "Contacts base" string?


Another approach we researched that we would rather not use is opening up the ActiveRecord::Errors class and writing our own implementation of the errors#full_messages function. (This blog post describes the technique.) This approach changes the behavior of the ActiveRecord::Errors class for the entire project, and we would rather use an approach that has a much more local impact. If we can't use the lcoalization file to achieve what we want, is there a more straightforward way to do so than opening up the ActiveRecord:Errors class?


EDIT

The contact.errors hash is:

$ contact.errors.to_yaml
--- !ruby/object:ActiveModel::Errors
base: !ruby/ActiveRecord:Contact
  attributes:
    id:
    # snip
messages: !omap
- :base:
  - Please include a phone number or emai.
like image 822
Kevin Avatar asked Jun 09 '14 21:06

Kevin


1 Answers

Looks like your validator is making :base appear as an attribute, override it with this locale.

# config/locales/en.yml
en:
  activerecord:
    attributes:
      contacts:
        base: "" 
like image 138
BookOfGreg Avatar answered Oct 19 '22 22:10

BookOfGreg