我有一个如下的数据模型
- 出价与出价的
User
相关联 - 出价可以是单个
Product
上的offer
或listing
Product
可能有多个用户发布的多个优惠和列表(单独的)- 用户可以在多个
Products
上放置优惠和列表
产品<---出价--->用户
给定来自Product
模型的现有p
,类似p.offers << bid
的操作(其中bid
是Bid
类的新实例)不会将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