无法在错误消息上添加属性值

时间:2015-01-23 15:57:40

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

我在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的实际值。我错过了什么?

1 个答案:

答案 0 :(得分:0)

您应该调用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