Search code examples
ruby-on-railsruby-on-rails-3activerecordmongoidactivemodel

Embedded mongoid document not marked as dirty / not updating


I have a data model as follows

  • A bid is associated with the User that placed the bid
  • A bid may be either an offer or a listing on a single Product
  • A Product may have multiple offers and listings (separate) posted by multiple users
  • A user may place offers and listings on multiple Products

Product <--- Bid ---> User

Given an existing p from the Product model, operations like p.offers << bid where bid is a new instance of the Bid class do not mark p as "dirty" and changes are not persisted to the database

Product class

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

Bid class

class Bid
  include Mongoid::Document
  belongs_to :user
  belongs_to :product

  field :amount, type: Money  
  field :timestamp, type: DateTime, default: ->{ Time.now }
end

Additionally, calling bid.save! or creating a new array p.offers = Array.new [bid] do not seem to work either


Solution

  • Updated:

    Your model structure should be

    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