Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails custom validation error messages on attributes of another model

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?

like image 599
stephenmurdoch Avatar asked Nov 21 '14 09:11

stephenmurdoch


1 Answers

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
like image 72
janfoeh Avatar answered Oct 24 '22 07:10

janfoeh