是否可以使用f.label中的道具名称显示错误消息?
我想显示" abc无效"而不是"电子邮件无效"," xyz太短(最少是6个charachtars)"而不是"密码太短(最少是6个charachtars)"。
模型\ user.rb
class User < ActiveRecord::Base
.
.
.
validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }, uniqueness: { case_sensitive: false }
validates :password, length: { minimum: 6 }
.
.
.
end
new.html.erb
<div class="row">
<div class="form-space">
<%= form_for(@user) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= render 'fields', f: f %>
<br>
<%= f.submit "create", class: "btn btn-warning" %>
</div>
<% end %>
</div>
_fields.html.erb
<%= f.label :email, "abc" %>
<%= f.text_field :email %>
<%= f.label :password, "xyz" %>
<%= f.password_field :password %>
_error_messages.html.erb
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-error">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li>* <%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
答案 0 :(得分:0)
您可以使用I18n翻译文件(config/locales/en.yml
)来“翻译”这些名称。显示错误消息时,ActiveRecord将首先查找activerecord.attributes.user.email
条目,然后默认为该字段的名称。
en:
activerecord:
attributes:
user:
email: "abc"
password: "xyz"