2013-03-01 95 views
0

我有三种模型 - 用法(月,电,气),项目(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”?

回答

0

我的天啊!我花了整整一天的时间试图找出这个问题....我通过将if语句中的“=”更改为“==”来解决此问题。 Feckin错别字!