Question

How would you validate the number of children that belong to a parent object?

For example, if I have a question object that accepts nested attributes for answers:

class Question < ActiveRecord::Base
  has_many :answers
  accepts_nested_attributes_for :answers, :allow_destroy => true
end

And I want to limit the number of answers, I might add a custom validation to the answer object, to inspect its parent and count the other answers like this:

class Answer < ActiveRecord::Base

  belongs_to :question
  validate :check_max_answers

  private


  def check_max_answers
    count = question.answers.select {|a| a != self}.count
    if (count > 10)
      errors.add(:answers, 'Too many answers!')
    end
  end

end

When check_max_answers runs, it only counts the other answers that have already been persisted.

Because the answers are being saved as nested attributes the validations all pass on the initial save because there are no questions saved, then they all get saved and thus become invalid!

Likewise the same problem happens if I put the validation on the question object, again because answers.count is always 0 before the initial save.

What am I doing wrong? Is there a workaround to perform this kind of validation?

Thanks for any help

Was it helpful?

Solution

Solved this one. The reason it was only counting answers in the DB was that I used .count instead of .size.

In my case I also need to discount answers marked for destroy. So the validation on the question looks like:

  def check_answers
    if answers.select{|a|not a._destroy}.size > 10
      errors.add(:answers, 'Too many answers')
    end
  end

This works as expected.

OTHER TIPS

The has_many association supports the option :limit, which if I have read your question correctly, should limit the results for you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top