在我的Rails(ActiveRecord)应用程序中,我有一个包含3列created_at,duration,interval的表预订 举个例子
| created_at | duration | interval |
| 22-5-2013 | 1 | month |
我想选择创建__等于(Date.today - duration.interval)的记录(此处为Date.today - 1.month)
我怎么能用where子句做到这一点?
我需要使用连接相同的表吗?
我没有任何线索。
答案 0 :(得分:2)
这里只是猜测,但您是否在寻找已过期的订阅? 如果是这样,我建议不要做你正在计划的事情,改变你的申请,从一开始就存储到期日。您可以轻松编写迁移以添加到期日期列并立即填写,然后您可以添加一个非常简单的范围来检查订阅是否已过期。
迁移:
add_column :subscriptions, :expiry_date, :datetime
Subscription.reset_column_information
Subscription.all.each do |subscription|
duration = 0
switch subscription.interval
case 'year'
duration = subscription.duration * 365
case 'month'
duration = subscription.duration * 30
case 'week'
duration = subscription.duration * 7
end
subscription.update_attribute(:expiry_date, subscription.created_at + duration.days)
end
型号:
scope :expired, lambda{ where("expiry_date <= ?", Time.now) }
答案 1 :(得分:1)
也许这对你有用(使用PostGre SQL):
Subscription.where("CAST(created_at AS DATE) = (CURRENT_DATE - interval '1 month')")
我无法让它与列一起工作,但也许这可以为你提供它的开始:
Subscription
.select("subscriptions.*, subscriptions.duration || ' ' || subscriptions.interval AS my_interval")
.where("CAST(created_at AS DATE) = (CURRENT_DATE + interval my_interval)")
然后有很多关于在区间函数中有一个变量的帖子:
Subscription.where("CAST(created_at AS DATE) = (CURRENT_DATE - (subscriptions.duration || ' ' || subscriptions.interval)::interval )")