【问题标题】:Validations with custom message and no attribute name带有自定义消息且没有属性名称的验证
【发布时间】:2014-07-16 16:08:07
【问题描述】:

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 blankCredit 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)"

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 rails-i18n


    【解决方案1】:

    所以经过太多时间后,我发现最好的答案应该是设置错误的格式。谁想要错误中的属性名称?我可以很容易地添加它,谁真正命名他们希望最终用途看到的属性?无论如何,这会重新格式化错误消息:

    en:
      errors:
        format: "%{message}"
    

    默认值为“%{attribute} %{message}”,IMO 通常不需要它,应该更改。

    【讨论】:

    • 当然希望我可以将其范围限定为某些活动记录模型而不是所有内容。
    【解决方案2】:

    最好把错误信息放到en.yml中如下:

    en:
     activerecord:
       errors:
         models:
           payment:
             attributes:
              cc_name:
                blank: "Credit card name cannot be blank"
    

    然后就可以移除模型中的自定义消息了。

    【讨论】:

    • 我刚试过这个,它是放置 #{attribute_name} 然后是空白消息。 * Cc name 信用卡名称不能为空,用您的代码。 ://
    猜你喜欢
    • 2014-11-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多