2012-06-24 161 views
0

我有一段時間間隔的虛擬屬性的模型:設置虛擬屬性

attr_accessible :description, :time_end, :time_start, :duration 
belongs_to :timesheet 

def duration 
    if attribute_present?("time_start") and attribute_present?("time_end") 
    ChronicDuration.output(self.time_end - self.time_start) 
    else 
    ChronicDuration.output(0) 
    end 
end 

def duration=(d) 
    self.time_end = self.time_start + d 
end 

但是,創建一個新的對象時,Rails的嘗試開始之前設置時間,從而導致錯誤。如何確保在開始後持續時間設置爲

錯誤:

undefined method `+' for nil:NilClass 

PARAMS:

{"utf8"=>"✓", 
"authenticity_token"=>"dg+CysIxZORyV3cwvD+LdWckFdHgecGDFDBNOip+iKo=", 
"entry"=>{"time_start"=>"now", 
"duration"=>"2h", 
"description"=>""}, 
"commit"=>"Create Entry"} 

回答

1

有幾件事情

  • 值得唸叨:and VS在紅寶石&& - http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/
  • 一些交替使用attribute_present?方法

    # opposite of blank? - http://api.rubyonrails.org/classes/Object.html#method-i-present-3F 
    if time_start.present? && time_end.present? 
    
    # short hand syntax for present? 
    if time_start? && time_end? 
    

我不認爲你的問題是持續時間TIME_START前被設置,假設TIME_START是一個日期或時間的數據庫類型 嘗試這種在軌控制檯

entry = Entry.new 
entry.time_start = "now" 
# => "now" 
entry.time_start 
# => nil 

你將字符串傳遞給時間對象,rails/ruby​​只是將值設置爲零。 如果time_end和time_start是字符串,我仍然不認爲你的代碼會給你你想要的結果嗎?

def duration=(d) 
    self.time_end = self.time_start + d 
end 

# params: time_start = "now" 
# params: duration = "2h" 
# time_end would be: now2h 

,如果我說錯了時間= TIME_START設置之前運行,那麼另一個辦法就是使用before_save回調

class Entry < ActiveRecord::Base 
    before_save :set_time_end 

    attr_accessor :duration 
    attr_accessible :description, :time_end, :time_start, :duration 

    belongs_to :timesheet 

    def duration 
    if time_start? && time_end? 
     ChronicDuration.output(self.time_end - self.time_start) 
    else 
     ChronicDuration.output(0) 
    end 
    end 

    def set_time_end 
    return nil if time_start.blank? 
    self.time_end = self.time_start + self.duration 
    end 
end 
1

1)它不是聰明的名稱的屬性end因爲多數民衆贊成一個關鍵字,它可能會帶來一些麻煩。

2)請發表您的PARAMS哈希

+0

1)我同意是這樣的。實際名稱是time_end –