我有三種模型 - 用法(月,電,氣),項目(project_type,date_implemented,manual_elec_savings,manual_gas_savings)和monthly_project_savings(elec,gas,usage_id,project_id)。 該協會正在設置如下:Rails 3 - 根據關聯模型的屬性計算模型的屬性
Project has_many :monthly_project_savings,
has_many :usages, through :monthly_project_savings
Usage has_many :monthly_project_savings
has_many :projects, through :monthly_project_savings
monthly_project_saving belongs_to :usage, :project
我有一個方法,在我的項目模式,使一個項目被保存後,它會根據該project_type相關monthly_project_savings:
def calc_monthly_project_saving
//destroy all previous records
self.monthly_project_saving.destroy_all
//calculate monthly savings
Usage.all.each do |u|
if self.project_type = "General" && self.date_implemented <= u.month
self.monthly_project_savings.create(usage_id: u.id, elec: self.manual_elec_savings, gas: self.manual_gas_savings)
elsif self.project_type="Elec" && self.date_implemented <= u.month
self.monthly_project_savings.create(usage_id: u.id, elec: u.elec, gas:0)
elsif self.project_type="Gas" && self.date_implemented <= u.month
self.monthly_project_savings.create(usage_id: u.id, elec: 0, gas:u.gas)
end
end
end
我然後使用after_save :calc_monthly_project_saving
來調用它。
我的問題是,如果我使用「after_save」調用方法,第一個if語句將始終傳遞true,即使project_type不同。除此之外,如果我將第一個self.monthly_project_savings.create(elec:)
從self.manual_elec_savings
更改爲u.elec
,那麼它將返回monthly_project_savings爲電子版。
如果我改變它來調用before_save,那麼它會拋出錯誤:"You cannot call create unless the parent is saved"
,這是有道理的。儘管在編輯現有項目記錄時它將以這種方式工作,但有時date_implemented將更改爲「t」或「f」。我不知道如何做到這一點,幫助?
另外,爲什麼如果我在編輯現有記錄時調用before_save方法,rails爲什麼將date_implemented的值設置爲「f」?