【问题标题】:Rails 4 ActiveRecord/Arel: Scoping models by their associated window's open/close dateRails 4 ActiveRecord/Arel:通过关联窗口的打开/关闭日期确定模型的范围
【发布时间】:2015-08-10 00:08:02
【问题描述】:

在我的 Rails 4 应用程序中,由 Postgres 数据库支持,我有一个 Assignmenthas_many :windows。每个Window 都有一个open_dateclose_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_dateWindow.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.currentAssignment.future 作用域都将在结果集中返回这个特定的赋值,因为它有一个当前窗口和一个未来窗口。

我希望仅在我拨打Assignment.current 电话时显示此特定任务。我还希望 Assignment.future 范围返回所有窗口都在未来的分配。

感谢您的帮助。另外,如果有人对这个问题有更好的标题,我愿意接受建议:)。谢谢。

【问题讨论】:

  • 所以您正在寻找 future 以仅返回 MIN(open_date) 在未来的记录?
  • 是的!好的。在 Rails 中,有组织的方式是什么?

标签: ruby-on-rails ruby-on-rails-4 activerecord


【解决方案1】:

如果您使用字符串定义查询条件,则相当简单:

scope :future,  -> { joins(:windows).where("windows.open_date >= ?", Time.now) }
scope :current, -> { joins(:windows).where("? BETWEEN windows.open_date AND windows.close_date", Time.now) }
scope :past,    -> { joins(:windows).where("windows.close_date <= ?", Time.now) }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-31
    • 2014-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多