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