简体   繁体   中英

Comparing datetime variables in Rails

Rails 3 Ruby 1.92 - i have a helper method comparing a datetime attribute on an object to the current date & time.

module StoreHelper
  def initial_time(product)
    if product.time_type == "Min"
      initial_time = (product.time * 60) 
    elsif product.time_type == "Hrs"
      initial_time = (product.time * 3600)
    else
      initial_time = 0
    end
  end

  def time_based_price(product)
    start_time = product.start_time
    current_time = Time.now
    expire_time = start_time + initial_time(product)

    if (current_time <= expire_time) && (unit_sales(product)>= product.volume)
      time_based_price = (product.price - product.boost_savings)
    else
      time_based_price = product.price
    end
  end
end

when i call it from my view i get error "undefined method `to_datetime' for 0:Fixnum". if i change the comparison line (current_time <= expire_time)to (expire_time >= current_time) i get error"comparison of Fixnum with Time failed"

I've tried using .now, .current, .zone.now for both Time and DateTime with no luck. When i call the Time.zone.now and expire_time values from my view they have the same format:

   2013-11-17 20:48:07 UTC - Time.zone.now
   2013-11-17 16:15:00 UTC  - expire_time

Are you calling this method for each product item in a list? In that case, looks like for one of the product, no values have been set for start_time, and time_type. You would get this error when expire_time is 0. But since you have tried the value of expire_time, I believe it must be happening for more product instances and it fails for one of those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM