嵌入的mongoid文档未标记为脏/未更新



我有一个如下的数据模型

  • 出价与出价的User相关联
  • 出价可以是单个Product上的offerlisting
  • Product可能有多个用户发布的多个优惠和列表(单独的)
  • 用户可以在多个Products上放置优惠和列表

产品<---出价--->用户

给定来自Product模型的现有p,类似p.offers << bid的操作(其中bidBid类的新实例)不会将p标记为"脏",并且更改不会持久化到数据库

产品类别

class Product
  include Mongoid::Document
  ...
  embeds_many :offers, class_name: 'Bid'
  embeds_many :listings, class_name: 'Bid'
end

投标等级

class Bid
  include Mongoid::Document
  belongs_to :user
  belongs_to :product
  field :amount, type: Money  
  field :timestamp, type: DateTime, default: ->{ Time.now }
end

此外,调用bid.save!或创建新数组p.offers = Array.new [bid]似乎都不起作用

更新:

你的模型结构应该是

class Product
   include Mongoid::Document
   ...
   has_many :offers, class_name: 'Bid', :inverse_of => :offers_bid
   has_many :listings, class_name: 'Bid', :inverse_of => :listings_bid
end
class Bid
   include Mongoid::Document
   belongs_to :offers_bid, :class_name => 'Product', :inverse_of => :offers
   belongs_to :listings_bid, :class_name => 'Product', :inverse_of => :listings
   belongs_to :user
   field :amount, type: Money  
   field :timestamp, type: DateTime, default: ->{ Time.now }
end

最新更新