I have a model with a virtual attribute for a time interval:
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
However, when creating a new object, Rails tries to set duration before start, leading to an error. How can I make sure that duration is set after start?
error:
undefined method `+' for nil:NilClass
params:
{"utf8"=>"✓",
"authenticity_token"=>"dg+CysIxZORyV3cwvD+LdWckFdHgecGDFDBNOip+iKo=",
"entry"=>{"time_start"=>"now",
"duration"=>"2h",
"description"=>""},
"commit"=>"Create Entry"}
A few things
andvs&&in ruby – http://devblog.avdi.org/2010/08/02/using-and-and-or-in-ruby/some alternates to using attribute_present? method
I don’t think your problem is with duration being set before time_start, assuming time_start is a datetime or time database type
try this in rails console
you are passing strings into time objects and rails / ruby just sets the value to nil.
If time_end and time_start were strings I still don’t think your code would give you the result you want?
if I am wrong about duration= running before time_start is set, an alternative would be something like this using a before_save callback