Rails 3 - 根据关联模型的属性计算模型的属性

时间:2013-03-01 18:44:17

标签: ruby-on-rails-3 activerecord model

我有三个模型 - Usage(月,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”?

1 个答案:

答案 0 :(得分:0)

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

相关问题