开发者

Comparing datetimes does not work

I'm creating a Rails application which uses MySQL. I have a table in my DB like this:

  create_table "pastes", :force => true do |t|
    t.string   "title"
    t.text     "body"
    t.string   "syntax"
    t.boolean  "private"
    t.datetime "expire"
    t.string   "password"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

I want to show only the non-expired pastes to people, so I do this:

@pastes = Paste.find(:all, :conditions => "expire < '#{Time.now.to_s(:db)}'")

However, even that returns ALL paste开发者_C百科s. Not just those that are not expired yet. Can anyone help me? Thanks

Oh, changing < to > returns no pastes, not even the non-expired ones :(


I would create a named scope within your Paste model:

class Paste < ActiveRecord::Base
  named_scope :expired, lambda {
    { :conditions => ["expire < ?", Time.zone.now] }
  }
end

Rails 3 version:

class Paste < ActiveRecord::Base
  scope :expired, lambda {
    where("expire < ?", Time.zone.now)
  }
end

Note that the lambda is required to delay the evaluation of Time.zone.now until when the (named) scope is actually invoked. Otherwise, the time that the class was evaluated would be used.

Now you can get all the expired pastes with a simple:

@pastes = Paste.expired

—Pretty clean, huh?


I solved it already. It had to do with timezones. This works:

@pastes = Paste.find(:all, :conditions => "expire > '#{Time.now.utc.to_s(:db)}'")
#                                                               ^^^ this does it
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜