大家好!我有一个模特:
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
我的问题是:如何制作:price3始终由price1 + price2的总和自动填充。 非常感谢您的帮助!
答案 0 :(得分:0)
您想使用callbacks界面。暴露了各种回调,例如:
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
这导致&#34; price3&#34;字段被设置为其他两个值的总和。