-
Type: New Feature
-
Resolution: Unresolved
-
Priority: Major - P3
-
None
-
Affects Version/s: 7.0.6
-
Component/s: Persistence, Validations
-
None
Summary
When documents are added to HABTM associations, for example via <<, validations on the affected documents are not run. This may result in documents participating in the association to be invalid after the addition.
This behavior is consistent with AR.
Behavior requested in this ticket is to validate documents prior to persisting addition to to HABTM associations. The difficulty in implementing this behavior is the lack of autosaving in Mongoid by default - if any of the documents fail validation, it would be up to the application to keep track of which documents are not saved and save them manually, or potentially lose data.
Details
Example:
You have a post document and a user document that have a has_and_belongs_to_many association. You want a post to only be allowed to belong to a limited amount of users, 2 for this example. So you add a length validation on the user_ids array:
class User has_and_belongs_to_many :posts end class Post has_and_belongs_to_many :users validates :user_ids, length: { minimum: 1, maximum: 2 } end
If you create a post through the a user:
$ post = user.posts.create(...) => returns the post $ post.users << another_user => returns the post
Now the post has two users:
$ post.users.length => 2
If you add another user, it should fail. But it doesn't:
$ post.users << another_user => returns the post
What's weird is the post is persisted, but it is still not valid. If you call save, it fails, but the post is already saved:
$ post.persisted? => true $ post.valid? => false $ post.save! => // Mongoid validation error... $ post => ... user_ids: [1, 2, 3] ...
This is a really big issue in Mongoid. You cannot validate array fields!? I do not think this issue exists in active_record.
- is related to
-
MONGOID-3573 nullifying, deleting or destroying an embedded document doesn't trigger validations on base document
- Backlog
-
MONGOID-5374 HABTM fails length validation on create when association is not accessed from child
- Backlog