user2158382
user2158382

Reputation: 4510

Rails validation not running when creating new associations

I have a custom validation that makes sure I don't have too many associations in a HABTM association. Here is the validation in the Request model

  validate :max_tags

  MAXIMUM_AMOUNT_OF_TAGS = 5

  def max_tags
    debugger
    unless tags.count < MAXIMUM_AMOUNT_OF_TAGS
       errors[:base ] << "You cannot have more than #{MAXIMUM_AMOUNT_OF_TAGS} tags on this gift request." 
    end
  end

This validation runs whenever I create a new Request; however, it isn't executed whenever I create tags and associate it to the Request. Here is a block of code where the validation doesn't execute when create new associations

if @request.save
  if tags
    tags.each do |tag|
      tag = Tag.find_by_name(tag)
      if tag
        self.tags << tag
        tag.increment_gift_request_count
      end
    end
  end
end

Upvotes: 2

Views: 487

Answers (1)

Vakiliy
Vakiliy

Reputation: 871

You may validate number tags with before_add callback, like this:

MAXIMUM_AMOUNT_OF_TAGS = 5
has_and_belongs_to_many :tags, before_add: :validate_max_tags

private

def validate_max_tags(tag)
  if (tags.count > MAXIMUM_AMOUNT_OF_TAGS) 
    errors.add(:base, :max_tag_error)
    raise ActiveRecord::Rollback
  end
end

Upvotes: 1

Related Questions