[英]Validations with custom message and no attribute name
Ruby on Rails 4.1
该表单已在模型中检查了验证。 我有一些自定义消息,它们在消息之前显示属性名称。
我正在尝试在en.yml文件中指定属性的翻译,或者只是删除属性名称。 我没有收到错误,只是在没有自定义消息的情况下使属性人性化。
例如,我收到的一条消息是* Cc name your name on the credit card cannot be blank
,我要说的是Your name on the credit card cannot be blank
或Credit card name cannot be blank
。
模型:
class Payment < ActiveRecord::Base
validates_presence_of :telephone, :email, :address1, :city, :state, :postal_code, :country, :cc_type, :cc_number, :ccv, :expires_on, :ship_name, :ship_address1, :ship_city, :ship_state, :ship_postal_code, :ship_country
validates_presence_of :cc_name,
:message => ' Your name on the credit card cannot be blank'
validates_presence_of :name_auth,
:message => ' Your name authorizing the purchase cannot be blank'
错误消息文件:
<% if @payment.errors.any? %>
<div id="error_explanation">
<div class="alert alert-error">
The form contains <%= pluralize(@payment.errors.count, "error") %>
</div>
<ul>
<% @payment.errors.full_messages.each do |msg| %>
<li>* <%= msg.humanize %></li>
<% end %>
</ul>
</div>
<% end %>
en.yml文件:
en:
activerecord:
attributes:
cc_name: "Credit card name"
name_auth: "Authorizing name"
date_auth: "Authorized date"
card_holder_auth: "Authorized card holder"
charge_auth: "Authorizing payment"
cc_number: "Credit card number"
ccv: "Card code verification (CCV)"
因此,经过太多时间后,我发现最好的答案应该是设置错误的格式。 谁想要错误中的属性名称? 我可以轻松地添加它,而谁真正为它们的属性命名,最终用户希望看到什么呢? 无论如何,这会重新格式化错误消息:
en:
errors:
format: "%{message}"
默认值为“%{attribute}%{message}”,通常不希望使用IMO,应将其更改。
最好将错误消息放入en.yml中,如下所示:
en:
activerecord:
errors:
models:
payment:
attributes:
cc_name:
blank: "Credit card name cannot be blank"
然后,您可以在模型中删除自定义消息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.