zwayjg
Last Updated: February 25, 2016
·
1.148K
· akalyaev
D83b63db79b42978fe35e120550ca180

AssociationCountValidator

Custom Rails3 validator to validate records count in the association.

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

More about the problem (http://homeonrails.com/2012/10/validating-nested-associations-in-rails/) and this validator (http://homeonrails.com/2012/10/associationcountvalidator/).

Say Thanks
Respond

1 Response
Add your response

429
781f66c42983ae7ee3123bbd620d8568

I had a similar question I posted on StackOverflow last year. I included my own implementation there: http://stackoverflow.com/questions/5932509/rails-validating-at-least-one-habtm-relationship

Yours definitely looks more concise, and I see it takes into account records that are marked for deletion, which mine does not.

over 1 year ago ·