如何使用Mongoid字段类型Set?

问题描述 投票:0回答:1
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

ruby-on-rails mongoid
1个回答
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 方法在序列化时返回原始属性,因此应该期望获得数组而不是集合。

© www.soinside.com 2019 - 2024. All rights reserved.