【发布时间】:2015-08-10 00:08:02
【问题描述】:
在我的 Rails 4 应用程序中,由 Postgres 数据库支持,我有一个 Assignment 和 has_many :windows。每个Window 都有一个open_date 和close_date。
每个Window 模型都有三个作用域:
scope :future, -> { where(open_date.gt(Time.zone.now)) }
scope :current, -> { where(open_date.lt(Time.zone.now).and(close_date.gt(Time.zone.now)))}
scope :past, -> { where(close_date.lt(Time.zone.now)) }
在这些范围内,Window.open_date 和 Window.close_date 是定义为:Window.arel_table[:open_date] 和 Window.arel_table[:close_date] 的类似方法。
我的Assignment 模型有三个作用域:
scope :future, -> { joins(:windows).merge(Window.future) }
scope :current, -> { joins(:windows).merge(Window.current) }
scope :past, -> { joins(:windows).merge(Window.past) }
假设一个特定的Assignment 实例的windows 查询产生以下结果:
-> assignment.windows
[#<Window
id: "398b76fe-8a00-4c1b-8901-d040c5f236f6",
open_date: Sat, 08 Aug 2015 23:46:02 UTC +00:00,
close_date: Mon, 10 Aug 2015 23:46:02 UTC +00:00,
assignment_id: "8b73b223-e48d-4cc0-8178-16eba9a5832b">,
#<Window
id: "08917f79-a9b0-41ce-a3ab-aa7821e23fba",
open_date: Mon, 10 Aug 2015 23:46:02 UTC +00:00,
close_date: Wed, 12 Aug 2015 23:46:02 UTC +00:00,
assignment_id: "8b73b223-e48d-4cc0-8178-16eba9a5832b">]
Assignment.current 和 Assignment.future 作用域都将在结果集中返回这个特定的赋值,因为它有一个当前窗口和一个未来窗口。
我希望仅在我拨打Assignment.current 电话时显示此特定任务。我还希望 Assignment.future 范围返回所有窗口都在未来的分配。
感谢您的帮助。另外,如果有人对这个问题有更好的标题,我愿意接受建议:)。谢谢。
【问题讨论】:
-
所以您正在寻找
future以仅返回MIN(open_date)在未来的记录? -
是的!好的。在 Rails 中,有组织的方式是什么?
标签: ruby-on-rails ruby-on-rails-4 activerecord