1

My custom message for scoped uniqueness validation is not displayed.

I'm including what I think is the relevant code, but please let me know if you think there's something else that you might need to see.

class Beverage < ActiveRecord::Base
  has_many :grapeages, dependent: :destroy
  has_many :wine_varietals, through: :grapeages
  validates_associated :grapeages
end

class Grapeage < ActiveRecord::Base
  belongs_to :beverage
  belongs_to :wine_varietal

  # Neither of these seem to work:
  #validates :wine_varietal_id, uniqueness: {scope: :beverage_id, message: 'xxx'}
  validates_uniqueness_of :wine_varietal_id, scope: :beverage_id, message: 'xxx'
end

Rather than 'xxx', the displayed error message is:

Grapeages is invalid
user664833
  • 18,397
  • 19
  • 91
  • 140
  • What does 'is not displayed' mean? You don't see it in your view or doesn't appear when you query `grapeage.errors`? Show us your view if it is present in `grapeage.errors` – Damien Dec 15 '11 at 01:51

1 Answers1

2

I found a solution after searching around validates_associated.. my searches led me to 3668018 and I followed up on its first post, which provides a nice fix for the fact that currently validates_associated overrides the actual error messages with [Model] is invalid. As a bonus, the same link shows a nice way to remove duplicate error messages (note that the class had to be updated to ActiveModel::Errors).

# config/initializers/validation_fixes.rb
module ValidatesAssociatedAttributes
  module ActiveRecord::Validations::ClassMethods
    def validates_associated(*associations)
      class_eval do
        validates_each(associations) do |record, associate_name, value|
          (value.respond_to?(:each) ? value : [value]).each do |rec|
            if rec && !rec.valid?
              rec.errors.each do |key, value|
                record.errors.add(key, value)
              end
            end
          end
        end
      end
    end
  end
end

# remove duplicate error messages
class ActiveModel::Errors
  alias old_full_messages full_messages
  def full_messages
    old_full_messages.uniq
  end
end

Don't forget to restart the server.

Community
  • 1
  • 1
user664833
  • 18,397
  • 19
  • 91
  • 140