Search code examples
ruby-on-railsmongoid

How to use Mongoid field type Set?


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]

Is there any better way to access f.bars?

Mongoid 9.0.0


Solution

  • Your code isn't actually reproducable.

    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]}
    irb(main):013:0> Mongoid::VERSION
    => "9.0.0"
    

    The attributes method returns the raw attributes as they are serialized so getting an array instead of a set should be expected.

    Just like with ActiveRecord you can access attributes through the getter method, the :[] method or read_attribute.