1
votes

I'm using rails 3 with devise.

I have a User table with fields: email, password, fname, lname

I currently output errors in my view as follows:

<% if @user.errors.any? %>
    <div id="error_explanation" class="error">
    <h2>Hold on!</h2>
        <ul>
            <% @user.errors.full_messages.each do |msg| %>
                <li><%= msg %></li>
            <% end %>
        </ul>
    </div>
<% end %>

Problem is this renders as:

Email The User's Email cannot be blank
Password The User's Password cannot be blank
Fname The User's Fname is too short (minimum 1 characters)
Lname The User's Lname is too short (minimum 1 characters)

How can I get the field name to not appear first with every error?

In my user model I have:

validates :fname, :length => { :minimum => 1, :maximum => 100 } validates :lname, :length => { :minimum => 1, :maximum => 100 }

I can customize those fields with a message attribute. What about email and password which appear to be built into devise? How do I customize those error messages?

Thanks

2

2 Answers

2
votes

http://ar.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

validates_presence_of(*attr_names)

 Configuration options:
  message - A custom error message (default is: "can‘t be blank").

As for the built in names customisation, this thread can help

Rails3: Devise internationalization does not localize "Password confirmation" and others

(to extend)

activerecord:
   attributes:
       user:
        email: "your_way_of_email"
          password: "your_way_of_password"
          password_confirmation: "your_way_of_password_confirmation"

Rails will then humanize them

0
votes

Use each_key to retrieve fields and navigate errors on each field.

<% if @user.errors.any? %>
    <div id="error_explanation" class="error">
    <h2>Hold on!</h2>
        <ul>
            <% @user.errors.each_key do |attr| %>
                <% @user.errors[attr].each do |msg| %>
                    <% next if msg.nil? %>

                    <li><%= msg %></li>
                <% end %>
            <% end %>
        </ul>
    </div>
<% end %>

View the source of full_messages: http://ar.rubyonrails.org/classes/ActiveRecord/Errors.html#M000311