【问题标题】:mongoid embeds_many associated collection remain emptymongoid embeds_many 关联集合保持为空
【发布时间】:2016-06-20 08:56:15
【问题描述】:

我有两个模型

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

class Image
 include Mongoid::Document
 embedded_in :supplier
end

当我以嵌套形式保存图像时,它会嵌入到供应商集合中,即

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

但问题是图像集合本身仍然是空的,即

 Image.count # gives 0

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid mongoid5


    【解决方案1】:

    您的Image 模型的文档存储在您的Supplier 模型的文档中。所以基本上没有在 mongo 中创建的名称为 images 的集合。在您的 mongo 控制台中检查。您将只有suppliers 收藏,而没有images 收藏。

    如果您想直接访问图像而不访问特定图像,您可以这样做

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

    或者实现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
    

    【讨论】:

    • 是 mongoid 的默认行为吗?这对我来说没有意义。如果需要,我可以创建一个数组字段。但我想根据 id 获取图像记录。 Image.find 不是 Supplier.first.images.find
    • 您要查找的是has_many 而不是embedds_many
    • 是的,这是最后一个可用的选项
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多