我有一个模型 Product,它既有:created_at
时间戳又有:expiration_in_days
属性。产品在创建后的特定天数被视为过期。如何编写只返回未过期产品的查询?
导轨 4,红宝石 2.1,PG 0.17
我一直在尝试这样的查询,但没有成功:
#product.rb
def self.not_expired
where('created_at + expiration_in_days * 86400 >= ?', Time.now)
end
我有一个运行良好的纯 Ruby 版本,只是速度较慢:
#product.rb
def self.not_expired
select{ |p| (p.created_at.to_i + p.expiration_in_days * 86400) >= Time.now.to_i}
end
- 注意,86400 计算将 :expiration_in_days 整数转换为秒
任何关于比文档 ( http://guides.rubyonrails.org/active_record_querying.html )更高级的 Rails 查询的指针也将受到欢迎。
提前致谢。