Rails custom validation error messages on attributes of another model

rails-activerecord, rails-i18n, ruby-on-rails, validation

Solution

ActiveModel looks up validation errors in several scopes. `Foo` and `Bar` can share the same error message for `mode_mismatch` if you include it at `activerecord.errors.messages` instead of `activerecord.errors.models`:

en:
  activerecord:
    errors:
      messages:
        mode_mismatch: "Foo %{link} has the wrong mode."

Using that locale string with the `link` interpolation then becomes a matter of

def mode_matcher
  self.foos.each do |foo|
    next unless foo.mode == "http"

    errors.add :base, :mode_mismatch, link: Rails.application.routes.url_helpers.foo_path(f)
  end
end

Problem

I'm using using the following code in my model to insert a link into a validation error message: ``` class Bar < ActiveRecord::Base has_many :foos validate :mode_matcher def mode_matcher self.foos.each do |f| errors[:base] << mode_mismatch(foo) unless foo.mode == "http" end end def mode_mismatch(f) foo_path = Rails.application.routes.url_helpers.foo_path(f) "Foo <a href='#{foo_path}'>#{f.name}</a> has the wrong mode.".html_safe end ``` It works well but I know that the recommended way of doing this is through a locale file. I'm having trouble with that because I'm validating an attribute of another model, so the following doesn't work: ``` en: activerecord: errors: models: bar: attributes: foo: mode_mismatch: "Foo %{link} has the wrong mode." ``` What's the correct way to do this?

Original source