I noticed that when using exclude or only to remove some attributes which are actually embeds many associations, we end up with an empty array instead of a MissingAttributeError exception like for other attributes (this is a great feature by the way!).
This is a bit misleading as there's no explicit way to distinguish between a missing field and an empty association. This exception is a great way to protect the code. So I believe this is a small "bug".
I check the specs from the code and found some covering the missing attribute INSIDE an embeds many relation, but no spec covering the missing relation itself.
Here is a reproduction script I wrote using the same models from your specs so you can easily turn it into a spec:
#!/usr/bin/env ruby require 'bundler/inline' gemfile do source 'https://rubygems.org' gem 'mongoid', '7.2.0' end require 'mongoid' Mongoid.configure { |c| c.clients.default = { hosts: ['localhost'], database: 'test' } } puts Mongoid::VERSION puts Mongo::VERSION # From https://github.com/mongodb/mongoid/blob/master/spec/mongoid/association/embedded/embeds_many_models.rb class EmmCongress include Mongoid::Document include Mongoid::Timestamps embeds_many :legislators, class_name: 'EmmLegislator' field :name, type: String end class EmmLegislator include Mongoid::Document embedded_in :congress, class_name: 'EmmCongress' field :a, type: Integer, default: 0 field :b, type: Integer, default: 0 end # From https://github.com/mongodb/mongoid/blob/master/spec/mongoid/association/embedded/embeds_many_query_spec.rb # setup congress = EmmCongress.new(name: 'foo') congress.legislators << EmmLegislator.new(a: 1, b: 2) congress.save! # let congress = EmmCongress.where(name: 'foo').only(:id).first p congress.legislators # => what I expect: ActiveModel::MissingAttributeError # => what is returned: [] # p congress.name # in comparison, this is raising ActiveModel::MissingAttributeError as expeted
This is the output I'm getting:
> ./mongoid_embeds_many_only.rb 7.2.0 2.14.0 []
Whereas I would expect an exception here, like for other attributes.
What do you think?
- causes
-
MONGOID-5306 Use pluck instead of only to avoid projecting when referencing association _ids
- Closed
- related to
-
MONGOID-4704 Project referenced associations with #only
- Backlog