使用Rails我试图得到一个错误消息,如“歌曲字段不能为空”保存。做以下事情:
validates_presence_of :song_rep_xyz, :message => "can't be empty"
... 只显示“Song Rep XYW不能为空”,这是不好的,因为字段的标题不是用户友好的。如何更改字段本身的标题?我可以更改数据库中字段的实际名称,但我有多个“song”字段,我确实需要特定的字段名称。
我不想破坏rails的验证过程,我觉得应该有办法解决这个问题。
使用Rails我试图得到一个错误消息,如“歌曲字段不能为空”保存。做以下事情:
validates_presence_of :song_rep_xyz, :message => "can't be empty"
... 只显示“Song Rep XYW不能为空”,这是不好的,因为字段的标题不是用户友好的。如何更改字段本身的标题?我可以更改数据库中字段的实际名称,但我有多个“song”字段,我确实需要特定的字段名称。
我不想破坏rails的验证过程,我觉得应该有办法解决这个问题。
当前回答
关于被接受的答案和列表中的另一个答案:
我正在确认nanamkim的custom-err-msg的分支与Rails 5和区域设置一起工作。
您只需要用一个插入符号开始locale消息,它不应该在消息中显示属性名称。
模型定义为:
class Item < ApplicationRecord
validates :name, presence: true
end
用下面的en.yml:
en:
activerecord:
errors:
models:
item:
attributes:
name:
blank: "^You can't create an item without a name."
item.errors。Full_messages将显示:
You can't create an item without a name
你不能创建一个没有名称的项目
其他回答
在你的模型中:
validates_presence_of :address1, message: 'Put some address please'
在你看来
<% m.errors.each do |attr, msg| %>
<%= msg %>
<% end %>
如果你这样做
<%= attr %> <%= msg %>
您将得到带有属性名的错误消息
address1 Put some address please
如果您想获取单个属性的错误消息
<%= @model.errors[:address1] %>
一个解决方案可能是改变i18n的默认错误格式:
en:
errors:
format: "%{message}"
默认格式:%{attribute} %{message}
升级了@Federico回答为所有字段错误的通用答案。
在你的控制器中。
flash[:alert] = @model.errors.messages.values
# [["field1_err1", "field1_err2"], ["field2_err1"], ["field3_err1"]]
与rails docs中一样,messages方法“返回属性的散列及其错误消息数组”。
然后,在表单中显示这些错误:
<% flash.each do |type, type_arr| %>
<% type_arr.each do |msg| %>
<ul>
<li>
<%= msg.to_sentence %>
</li>
</ul>
<% end %>
<% end %>
用正常的方式做就好:
validates_presence_of :email, :message => "Email is required."
但是要像这样显示它
<% if @user.errors.any? %>
<% @user.errors.messages.each do |message| %>
<div class="message"><%= message.last.last.html_safe %></div>
<% end %>
<% end %>
返回
"Email is required."
本地化方法绝对是做到这一点的“正确”方法,但如果你做的是一个小的、非全局的项目,并且想要快速进行——这肯定比文件跳转更容易。
我喜欢它的能力,把字段名放在其他地方,而不是字符串的开始:
validates_uniqueness_of :email, :message => "There is already an account with that email."
关于被接受的答案和列表中的另一个答案:
我正在确认nanamkim的custom-err-msg的分支与Rails 5和区域设置一起工作。
您只需要用一个插入符号开始locale消息,它不应该在消息中显示属性名称。
模型定义为:
class Item < ApplicationRecord
validates :name, presence: true
end
用下面的en.yml:
en:
activerecord:
errors:
models:
item:
attributes:
name:
blank: "^You can't create an item without a name."
item.errors。Full_messages将显示:
You can't create an item without a name
你不能创建一个没有名称的项目