I am not able to subtract two dates from each other using Ruby...why?
this is the code I have. It is a method for a contact.rb (Contact is a model):
def event_delay event
# find instance of contact_event
puts "+++++++++++++++inside event_delay method"
event_class = event.class.name
event_id = event_class.foreign_key.to_sym
#puts event_id
contact_event_class = "Contact#{event_class}".constantize
#puts contact_event_class
contact_event = contact_event_class.first(:conditions =>
{:contact_id => self.id,
event_id => event.id})
#puts "inspect contact_event"
#puts contact_event.inspect
if !contact_event.nil?
puts "---- #{contact_event.title} not nill"
puts contact_event.id
date_sent = contact_even开发者_StackOverflow社区t.date_sent
target_send_date = self.date_entered + event.days
puts "date_sent:"
puts date_sent.to_date
puts "target send date:"
puts target_send_date
return date_sent - target_send_date
end
end
The goal is to return the difference in days between the time a date_sent to the time target_send_date. But I get the following error:
undefined method `-@' for Sun, 08 Aug 2010:Date
Maybe both values are not dates? The -
method is defined so that's why I'm thinking that you might not have two dates. Does this work in irb for you?
irb(main):001:0> require "date"
=> true
irb(main):002:0> Date.new(2010, 10, 20) - Date.new(2010, 9, 20)
=> Rational(30, 1)
irb(main):003:0>
After migrating to Rails 3.2, I got the same strange error when running specs, but was able to isolate it:
3.days.ago - Date.today
=> NoMethodError: undefined method `-@' for Sun, 29 Apr 2012:Date
'3.days.ago' produces an ActiveSupport::TimeWithZone object, which (apparently) does not mix with the Date object that Date.today gives you.
精彩评论