2012-06-21 93 views
0

我在模型中有一個before_validation。其目的是計算兩個DateTime對象之間的工作時間,並將該值插入time_worked屬性。它的成功取決於兩個領域的有效性,並且它揭示了第三個領域的價值,而第三個領域又具有驗證。在其他驗證之間執行before_validation?

class TimeEntry < ActiveRecord::Base 
    validates :start_time, :end_time, :presence => true 
    validates :time_worked, :presence => true, :numericality => true 
    before_validation :calculate_time_worked 

def calculate_time_worked 
    time_float = (Time.parse(self.end_time.to_s) - Time.parse(self.start_time.to_s))/1.hour 
    self.time_worked = ((time_float * 10).ceil).to_f/10 
end 

的問題是,如果任何start_timeend_time是空的或無效的我calculate_time_worked方法會失敗,這就是爲什麼這兩個領域都有驗證!

任何想法如何重構?

回答

0

它注意到before_validates在這些方法被設置之前被調用。如果我在哪裏使用before_save來calculate_time_worked。一旦attrs將設置和您的驗證將完成。

class TimeEntry < ActiveRecord::Base 
    validates :start_time, :end_time, :presence => true 
    validates :time_worked, :presence => true, :numericality => true 
    before_save :calculate_time_worked 

end 
1

從@PedroMedeiros的before_save解決方案將在這種情況下工作....但如果你想驗證time_worked是肯定的,那麼你可能會做這樣的事:

validate :calculate_time_worked 

    def calculate_time_worked 
    return if end_time.blank? || start_time.blank? 
    time_float = (Time.parse(self.end_time.to_s) - Time.parse(self.start_time.to_s))/1.hour 
    self.time_worked = ((time_float * 10).ceil).to_f/10 
    if time_worked < 0 
     self.errors.add(:end_time, "Must be after Start Time") 
    end 
    end 

最後 - 這個SO問題很酷getting the difference of time in hours

相關問題