ruby-on-railsmongodbmongoidmongoid5

mongoid embeds_many associated collection remain empty


I have two models

class Supplier < User
  include Mongoid::Document
  embeds_many :images
  accepts_nested_attributes_for :images
end

class Image
 include Mongoid::Document
 embedded_in :supplier
end

When I save images in nested form it gets save embeded in supplier collection i.e

 s = Supplier.first
 s.images #some Image records

But the problem is image collection itself remains empty i.e

 Image.count # gives 0

Solution

  • The documents of your Image model are stored inside the document of your Supplier model. So basically there is no collection with name images created in mongo. Check that in your mongo console. You only will be having a suppliers collection and no images collection.

    If you want to access Images directly without accessing a particular you can do this

    Supplier.all.pluck(:images)
    #It will give you an array of all images
    

    Or implement has_many

    class Supplier < User
      include Mongoid::Document
      has_many :images
      accepts_nested_attributes_for :images
    end
    
    class Image
      include Mongoid::Document
      belongs_to :supplier
    end