class Foo
include Mongoid::Document
field :bars, type: Set
end
f = Foo.new
f.add_to_set(bars: 1)
f.bars
=> nil
f.attributes['bars']
=> [1]
有没有更好的方法来访问f.bars?
Mongoid 9.0.0
您的代码实际上不可重现。
irb(main):007:0> f = Foo.new
irb(main):008:0> f.add_to_set(bars: 1)
=> #<Foo _id: 66dc4cc6fbdbbf68304b94bd, bars: [1]>
irb(main):009:0> f.bars
=> #<Set: {1}>
irb(main):010:0> f.read_attribute(:bars)
=> #<Set: {1}>
irb(main):011:0> f[:bars]
=> #<Set: {1}>
irb(main):012:0> f.attributes
=> {"_id"=>BSON::ObjectId('66dc4cc6fbdbbf68304b94bd'), "bars"=>[1]}
attributes 方法在序列化时返回原始属性,因此应该期望获得数组而不是集合。