Reputation: 13467
I want rails to show error message
Field <field name> can't be blank
but using standard means I get
<field name> Field <field name> can't be blank
Here's a minimal example reproducing the problem:
rails new test
cd test
rails g scaffold user name
rake db:migrate
Add validation to app/models/user.rb
:
class User < ActiveRecord::Base
validates :name, presence: true
end
Edit config/locale/en.yml
to be:
en:
activerecord:
attributes:
user:
name: "Name"
errors:
models:
user:
attributes:
name:
blank: "Field %{attribute} can't be blank"
After this start the server
rails s
point browser to http://localhost:3000/users/new and press "Create User" button. You'll get:
Apparently, there's another template somewhere, which says something like
%{attribute} %{message}
but I can't find it in rails code.
Upvotes: 1
Views: 451
Reputation: 4888
This is because in a standard view generated by scaffold (views/users/_form.html.erb
) you have:
<% user.errors.full_messages.each do |message| %>
This is what returns
Name Field Name can't be blank
Instead, you can modify the _form
view and use user.errors.messages
, where you get a hash with errors assigned to keys representing fields:
@user.errors.messages
{:name=>["Field Name can't be blank"]}
To get what you expect you could write for example:
<% @user.errors.messages.values.flatten.each do |message| %>
<li><%= message %></li>
<% end %>
Upvotes: 1