我有三个模型 - Usage(month, elec, gas), Project(project_type, date_implemented, manual_elec_savings, manual_gas_savings) 和monthly_project_savings(elec, gas, usage_id, project_id)。协会设立如下:
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
,那么它将以 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”?