我正在创建一个使用MySQL的Rails应用程序。我的数据库中有一个这样的表:
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
我只想向人显示未过期的
pastes
,所以我这样做:@pastes = Paste.find(:all, :conditions => "expire < '#{Time.now.to_s(:db)}'")
但是,即使返回ALL
pastes
。不仅是那些尚未过期的。谁能帮我?谢谢哦,将
<
更改为>
不会返回pastes
,甚至不会返回未过期的:( 最佳答案
我将在您的粘贴模型中创建一个命名范围:
class Paste < ActiveRecord::Base
named_scope :expired, lambda {
{ :conditions => ["expire < ?", Time.zone.now] }
}
end
Rails 3版本:
class Paste < ActiveRecord::Base
scope :expired, lambda {
where("expire < ?", Time.zone.now)
}
end
请注意,需要lambda来延迟对
Time.zone.now
的求值,直到实际调用(命名)作用域为止。否则,将使用评估该类的时间。现在,您可以使用以下简单方法获取所有过期的粘贴:
@pastes = Paste.expired
—很干净,是吗?
关于mysql - 比较日期时间不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2705514/