문제

I have a rake task that is supposed to go through my Task model, and if the time_frame attribute is in the past (DateTime.now > task.time_frame), should put some information. Here is the code:

task :change_it => :environment do
  @tasks = Task.already_expired
  @tasks.each do |task|
      puts "Kalabar" + task.inspect + "now time is:" + DateTime.now.to_s
  end
end

Task.already_expired is defined in the Task model like this:

def self.already_expired
    where("time_frame < ?", DateTime.now)
end

The problem is, it is printing all tasks, not just past tasks. Here is the output of running 'rake change_it':

Task Load (1.2ms)  SELECT "tasks".* FROM "tasks" WHERE (time_frame < '2013-12-04 17:25:37')
    Kalabar#<Task id: 3, title: "task 1 - past", content: "Should show this one", 
        created_at: "2013-12-04 17:05:53", updated_at: "2013-12-04 17:05:53", 
        schedule_id: 2, amount: nil, time_frame: "2013-12-02 08:15:00">
        now time is:2013-12-04T12:25:37-05:00
    Kalabar#<Task id: 5, title: "another task - past", 
        content: "should show this one", created_at: "2013-12-04 17:11:23", 
        updated_at: "2013-12-04 17:11:23", schedule_id: 3, amount: nil, 
        time_frame: "2013-12-03 02:07:00">now time is:2013-12-04T12:25:37-05:00
    Kalabar#<Task id: 6, title: "another task - future", 
        content: "should not show at first", created_at: "2013-12-04 17:11:23",
        updated_at: "2013-12-04 17:25:09", schedule_id: 3, amount: nil, 
        time_frame: "2013-12-04 12:27:00">now time is:2013-12-04T12:25:37-05:00

As you can see on the first line in the code snippet above, it is looking for

time_frame < '2013-12-04 17:25:37'.  

I have no idea where it is getting 17:25:37 from. How do I fix this? Thanks.

UPDATE:

I didn't realize that 17:25:37 was the current time in UTC. The problem is i need to convert the datetime that the user inputs into UTC before putting it into the database. Does anyone know how to do this?

UPDATE:

My question has changed since i posted this question. Here is the new question: rails - convert DateTime to UTC before saving to server

도움이 되었습니까?

해결책

You're getting 17:25:37 because DateTime.now returns a date-time object denoting the present time.

You could either use DateTime.now.to_date or DateTime.now.midnight if you want tasks with time_frame less than or equal to "Yesterday".

Update: To set time_frame to UTC, add the following model to your Task class. Please update the format in strptime appropriately, according to your need:

# app/models/task.rb

def time_frame=(value)
  write_attribute :time_frame, Date.strptime(value, "%m/%d/%Y").to_datetime.utc if value.present?
end
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top