【问题标题】:Storing addtional info about a document in Mongo Mapper through a many :in => Array通过 many :in => Array 在 Mongo Mapper 中存储有关文档的附加信息
【发布时间】:2010-02-12 15:54:31
【问题描述】:

我在 Pumps 和 Parts 之间有多对多的关系。我将零件 ID 存储在 Pump 文档中。我还想存储一个特定泵中使用了多少个零件。

简而言之,这就是我所拥有的

class Pump
  include MongoMapper::Document

  key :number, String
  key :desc, String
  key :part_ids, Array

  many :parts, :in => :part_ids 
end

class Part
  include MongoMapper::Document

  attr_accessor :pump_ids

  key :qty, Integer
  key :number, String
  key :desc, String

  def pumps
    Pump.all(:part_ids => self.id)
  end
end

在我意识到每个泵使用的零件数量不同之前效果很好,所以现在我需要存储每个关系的数量,也许还有一些其他关系特定的信息,比如注释。

我想要这样的东西,而不仅仅是存储和 id 数组。

[{:pump_id => "12hj3hjkbrw", :qty = 4},
 {:pump_id => "ggtyh5ehjrw", :qty = 10, :notes => "when using this part with this Pump please note this"}]

我不知道如何进行这项工作。

【问题讨论】:

    标签: mongodb mongomapper


    【解决方案1】:

    看起来你真的想要第三个模型,比如 PartUsage 或封装关系的东西。关键是您正在尝试存储和处理有关关系本身的一些数据,这需要另一个模型(EmbeddedDocument 是理想的)。

    你可以做这样的事情(注意:未经测试!):

    class Pump
      include MongoMapper::Document
    
      key :number, String
      key :desc, String
      key :part_usage_ids, Array
    
      many :part_usages
    end
    
    class Part
      include MongoMapper::Document
    
      key :qty, Integer
      key :number, String
      key :desc, String
    
      def pumps
        # not 100% sure of this query actually
        PartUsage.all(:part_id => self.id).collect { |pu| pu.pump }
      end
    end
    
    class PartUsage
      include MongoMapper::EmbeddedDocument
    
      belongs_to :pump
      belongs_to :part
      key :pump_id, ObjectId
      key :part_id, ObjectId
      key :qty, Integer
      key :notes, String
    end
    

    【讨论】:

    • 谢谢,我会尝试并告诉你。
    • 那么,你找到答案了吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多