Validador Rails3 personalizado para validar a contagem de registros na associação.
class AssociationCountValidator < ActiveModel::Validations::LengthValidator
MESSAGES = { :wrong_length => :association_count_invalid,
:too_short => :association_count_greater_than_or_equal_to,
:too_long => :association_count_less_than_or_equal_to }.freeze
def initialize(options)
MESSAGES.each { |key, message| options[key] ||= message }
super
end
def validate_each(record, attribute, value)
existing_records = record.send(attribute).reject(&:marked_for_destruction?)
super(record, attribute, existing_records)
end
end
Mais sobre o problema ( http://homeonrails.com/2012/10/validating-nested-associations-in-rails/ ) e este validador ( http://homeonrails.com/2012/10/associationcountvalidator/ ).