Ruby on rails Mongoid字段自动求和

Ruby on rails Mongoid字段自动求和,ruby-on-rails,ruby,mongodb,mongoid,Ruby On Rails,Ruby,Mongodb,Mongoid,各位!!我有一个模型: class Model include Mongoid::Document field :price1, :type =>Integer field :price2, :type =>Integer field :price3, :type =>Integer <== I want this field to be always result of price1 + price2 end 类模型 include Mongoid::Do

各位!!我有一个模型:

class Model
  include Mongoid::Document

field :price1, :type =>Integer 
field :price2, :type =>Integer 
field :price3, :type =>Integer <== I want this field to be always result of price1 + price2
 end
类模型
include Mongoid::Document
字段:price1,:type=>Integer
字段:price2,:type=>Integer
字段:price3,:type=>Integer您要使用该接口。公开了各种回调,例如:

require "mongoid"
require "pp"

Mongoid.configure.connect_to("test")

class Model
  include Mongoid::Document

  field :price1, type: Integer
  field :price2, type: Integer
  field :price3, type: Integer

  store_in collection: "mymodel"

  before_save do |document|
    document.price3 = document.price1 + document.price2
  end

end



model = Model.new

model.price1 = 2
model.price2 = 3

model.save
这将导致“price3”字段被设置为其他两个值的总和