-
Type: Bug
-
Resolution: Unresolved
-
Priority: Unknown
-
None
-
Affects Version/s: None
-
Component/s: None
-
None
When I have a HABTM association and on one side I validate that the association contains a certain number of targets, initial creation of a valid object fails:
task 'test:5374:1' => :environment do =begin Mongoid::Errors::Validations: message: Validation of Post failed. summary: The following errors were found: Users is too short (minimum is 1 character) resolution: Try persisting the document with valid data or remove the validations. =end class User include Mongoid::Document has_and_belongs_to_many :posts end class Post include Mongoid::Document has_and_belongs_to_many :users validates :users, length: { minimum: 1, maximum: 2 } end user=User.create! post = user.posts.create! end
If I validate user_ids instead of users there is no error:
task 'test:5374:2' => :environment do =begin No error =end class User include Mongoid::Document has_and_belongs_to_many :posts end class Post include Mongoid::Document has_and_belongs_to_many :users # Use user_ids instead of users validates :user_ids, length: { minimum: 1, maximum: 2 } end user=User.create! post = user.posts.create! end
If I force the users association to be populated, there would also be no error:
task 'test:5374:3' => :environment do =begin No error =end class User include Mongoid::Document has_and_belongs_to_many :posts end class Post include Mongoid::Document has_and_belongs_to_many :users # Use user_ids instead of users validates :users, length: { minimum: 1, maximum: 2 } before_validation do # access the association and force it to be populated users.to_a # insufficient: #users.length end end user=User.create! post = user.posts.create! end
Note in the last example, simply referencing length is insufficient even though it returns 1 - this apparently doesn't fill out enough of the actual association target for the validations to pass.
Test code: https://github.com/p-mongo/tests/blob/master/ma/lib/tasks/test_5374.rake
- related to
-
MONGOID-4925 Option to validate documents when adding to HABTM associations
- Backlog