【问题标题】:unable to add attribute value on Error message无法在错误消息上添加属性值
【发布时间】:2015-01-23 15:57:39
【问题描述】:

我在 user_calendar 模型上有一个自定义验证方法:

class UserCalendar < ActiveRecord::Base
  belongs_to :user

  validate :should_match_company_calendars
  ...

  private
    def should_match_company_calendars
      day_company_calendars = (..query..)
      errors.add(:user, :company_calendar_match) if day_company_calendars.count < 1
    end

这是 en.yml 上的消息:

company_calendar_match: "%{value.full_name} does not work in the selected time lapse"

验证工作正常,但消息显示 '%{value.full_name}' 而不是 full_name 的实际值。我错过了什么?

【问题讨论】:

    标签: ruby-on-rails validation model rails-i18n model-validation


    【解决方案1】:

    您应该调用I18n.t 方法并传递您想要显示的值,如下所示。

    # model
    errors.add(:user, I18n.t('... company_calendar_match', full_name: 'set value you want')) if day_company_calendars.count < 1
    
    # en.yml
    company_calendar_match: "%{full_name} does not work in the selected time lapse"
    

    更多详情Rails Guides - i18n api features

    【讨论】:

    • 谢谢@shoji!这成功了
    猜你喜欢
    • 2016-10-14
    • 1970-01-01
    • 2015-10-31
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 2019-06-09
    • 2015-08-19
    • 1970-01-01
    相关资源
    最近更新 更多