[英]Rails: How to display error message without model name, association name
I'd like to display error message without model name, association name. 我想显示错误消息,不带型号名称,关联名称。
For example, the following error was displayed, 例如,显示以下错误,
Rooms events base To time must be after from tim
But I'd like to display only To time must be after from time
. 但是我只想显示
To time must be after from time
。
The validate in my model is as followings; 我的模型中的验证如下:
validate do |e|
if e.start_at.present? && e.end_at.present? and e.start_at > e.end_at
errors[:base] << "To time must be after from time"
end
end
It would be appreciated if you could give me how to display only To time must be after from time
. 如果您能给我如何仅显示的信息,将不胜感激
To time must be after from time
。
application.html.erb application.html.erb
<% flash.each do |message_type, message| %>
<%= content_tag(:div, message, class: "alert alert-#{message_type}") %>
<% end %>
SOLVED! 解决了!
It works when I set the followings in en.yml 当我在en.yml中设置以下内容时,它可以工作
en:
errors:
format: "%{message}"
Add the following in your application.html above yield 在yield上方的application.html中添加以下内容
<% flash.each do |key, value| %>
<div class="alert alert-<%= key %>"><%= value %></div>
<% end %>
errors
is a hash. errors
是哈希。 The key is the name of the field name or :base
and the value is an array of your error messages as strings. 关键字是字段名或
:base
名称,值是错误消息的字符串数组。
values
on a hash will return an array of the values without the keys. values
上的散列将返回值的阵列没有密钥。 Because the value in this hash is an array, we end up with an array of arrays: [['To time must be after from time']]
因为此哈希中的值是一个数组,所以我们得到一个数组数组:
[['To time must be after from time']]
I use flatten
to squash all of the nested arrays to a single top level array. 我使用
flatten
将所有嵌套数组压缩为单个顶级数组。
join("\\n")
will join all of the array elements into a single string, separated by a newline character. join("\\n")
将所有数组元素合并为一个字符串,并用换行符分隔。
Put it all together and you get something like this: 将所有内容放在一起,您将得到以下内容:
flash[:error] = @object.errors.values.flatten.join("\n")
http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-values http://api.rubyonrails.org/classes/ActiveModel/Errors.html#method-i-values
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.