0

I am working in Mongoid 3 and Rails 3.

I want a validator to be called on a model after its collection is modified:

class TooManyValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    puts "validate called"
    if value.size > 4
      puts "too many???"
      record.errors[attribute] << 'too many'
    end
  end
end    

class Task
  include Mongoid::Document

  has_many :parts, inverse_of: :task
  validates :parts, too_many: true
end

class Part
  include Mongoid::Document

  belongs_to :task, inverse_of: :parts
end

The test i have is:

it "should not have too many parts" do    
  task = Task.create!

  puts "ADDING PARTS"
  6.times { task.parts << Part.create }
  #task.save

  puts "task.errors['parts'] = #{task.errors["parts"]}"

  Task.find(task._id).parts.size.should == 4
end

The output I get is:

validate called
ADDING PARTS
task.errors['parts'] = []

And the test fails with 6 != 4.

Also to be noted when I comment in the task.save line in the test I get

validate called
ADDING PARTS
validate called
too many???
task.errors['parts'] = ["too many"]

but it still fails with 6 != 4

How do I call the validator for :parts on Task after the parts collection is modified and get it not to update the collection after it fails?

Thanks

GTDev
  • 5,488
  • 9
  • 49
  • 84
  • BTW, you have another problem here - you're always creating part, which might or might not go into the parent object. Better use task.parts.build(params) – Roman Oct 19 '12 at 10:38
  • Your best bet would be to embed parts if possible and follow the answer of http://stackoverflow.com/questions/12985358/validating-embedded-document-in-mongoid-based-on-embedded-attribute – rubish Oct 20 '12 at 23:06

0 Answers0