在我的Rails 4 Postgres应用程序中,我有一个Project模型和一个WorkingDay模型,它们之间有has_many关系:
<select ng-model="demoData.StateName" ng-options="stateL.StateName as stateL.StateName for stateL in StateList">
<option value="" disabled hidden>State</option>
</select>
<select ng-model="demoData.Country" ng-options="countryL.Country as countryL.Country for countryL in CountryList">
<option value="" disabled hidden>Country</option>
</select>
working_day.rb
和class WorkingDay > ActiveRecord::Base
# working_times: text that is parsed into yml json format
belongs_to :project
end
project.rb
我遇到的问题是,使用正确的class Project > ActiveRecord::Base
has_many :working_days
# total_cost: decimal based on calculations of working_times of each working_day
before_save :calculate_total_cost
def calculate_total_cost
# carry out certain calculations based on working_days of this project
self
end
def regen_working_days(wd_json_data)
self.working_days.each(&:destroy)
wd_json_data.each do |wd_data|
self.working_days.create(wd_data)
end
self.save!
self
end
end
参数触发regen_working_days
后,wd_json_data
无法正确计算。它实际上是根据前一个total_cost
的值计算的,这意味着在实例中触发了这个方法,新的working_day对象尚未创建,旧的仍然存在。
有没有办法让working_days
方法的self.save!
部分在所有其他事务完成后才被触发?或者我通过我的方法处理嵌套对象和与它们相关的事务的方式总体上是错误的吗?