私には3つのモデルがあります-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モデルにメソッドがあり、プロジェクトを保存した後、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」を使用してメソッドを呼び出すと、project_typeが異なっていても、最初のifステートメントが常にtrueを渡すことです。これに加えて、最初のself.monthly_project_savings.create(elec:)
をからself.manual_elec_savings
に変更するとu.elec
、monthly_project_savingsがelecとして返されます。
before_saveを呼び出すように変更すると、エラーがスローされます:"You cannot call create unless the parent is saved"
、これは理にかなっています。既存のプロジェクトレコードを編集する場合はこのように機能しますが、date_implementedが「t」または「f」に変更される場合があります。私はこれを行う方法がわかりません、助けて??
また、余談ですが、既存のレコードを編集するときにメソッドbefore_saveを呼び出すと、railsがdate_implementedの値を「f」に設定するのはなぜですか?