-
Type: Bug
-
Resolution: Duplicate
-
Priority: Major - P3
-
None
-
Affects Version/s: 5.4.0, 6.4.4, 7.0.5
-
Component/s: Validations
-
None
-
Environment:Debian GNU/Linux 9 (stretch) 64-bit, Intel® Coreā¢ i7-8700 CPU @ 3.20GHz × 12, 15.6 GiB , ruby on rails 6.0.0
I am having an unexpected behavior when I am trying to update a nested relation that has some validation errors, I have a `has_many` relation between two entities (Dog and flea), and both models has their own validations as follows:
#Dog class Dog include Mongoid::Document field :name has_many :fleas, class_name: 'Flea' validates :name, presence: true accepts_nested_attributes_for :fleas, allow_destroy: true end
#Flea class Flea include Mongoid::Document field :name belongs_to :dog, class_name: 'Dog' validates :name, presence: true end
Using `nested_attributes` I have created 1 dog that has 2 fleas
d = Dog.create(name: 'Lulu', fleas_attributes: { 0 => { name: 'Tiny' }, 1 => { name: 'molly' } }) #get the persisted fleas d.fleas #Fleas { { :_id => BSON::ObjectId('5df40b96a5717a2ba148b25b'), :dog_id => BSON::ObjectId('5df40b96a5717a2ba148b25c'), :name => "Tiny" }, { :_id => BSON::ObjectId('5df40b96a5717a2ba148b25d'), :dog_id => BSON::ObjectId('5df40b96a5717a2ba148b25c'), :name => "molly" } }
Finally, I made an update using the dog instance without a name (breaking the presence validation associated to :name)
d.update(name: '', fleas_attributes: { 0 => { name: 'Tiny', _destroy: '1', id: '5df40b96a5717a2ba148b25b' }, 1 => { name: 'molly', id: '5df40b96a5717a2ba148b25d' } }) #response {color:red} =>false {color}
At the end, when I make a query for getting all the fleas associated to my dog, I got only one flea although the validation of the parent model has failed, that behavior is confused and it could be considered dangerous and tricky in more complex scenarios with more robust validations
d.fleas #response #_id|name |dog_id 5df40b96a5717a2ba148b25d | molly | 5df40b96a5717a2ba148b25c
- duplicates
-
MONGOID-4597 model#update commits changes in associations when top level model is invalid
- Backlog