开发者

Storing addtional info about a document in Mongo Mapper through a many :in => Array

开发者 https://www.devze.com 2022-12-20 12:43 出处:网络
I have a many to many r开发者_Python百科elationship between Pumps and Parts. I am storing the Part ids in the Pump document. I would also like to store how many Parts are used in a particular Pump.

I have a many to many r开发者_Python百科elationship between Pumps and Parts. I am storing the Part ids in the Pump document. I would also like to store how many Parts are used in a particular Pump.

Here's what I have, in short

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

Which worked fine until I realized the number of Parts used per Pump is different, So now I need store the qty per the relationship, and maybe some other relational specific info like notes.

Instead of just storing and Array of ids I'd like something like this instead.

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

I am not sure how to make this work.


It looks like you really want a third model here, like PartUsage or something to encapsulate the relationship. The key is that you're trying to store and work with some data about the relationship itself, and that requires another model (an EmbeddedDocument is ideal).

You could do something like this (beware: untested!):

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
0

精彩评论

暂无评论...
验证码 换一张
取 消