Search code examples
ruby-on-railsvalidationmodelrails-i18nmodel-validation

unable to add attribute value on Error message


i have a custom validation method on user_calendar model:

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

And this is the message on en.yml:

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

Validation works fine but the message shows '%{value.full_name}' instead of the actual value for full_name. What am i missing?


Solution

  • You should call I18n.t method and pass value you want to show like below.

    # 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"
    

    More detail is Rails Guides - i18n api features