【问题标题】:How to scope by_month from belongs_to associated model?如何将 by_month 从 belongs_to 关联模型限定范围?
【发布时间】:2013-10-30 01:30:19
【问题描述】:
ShiftNote belongs_to Shift has_many ShiftNote

我想要范围ShiftNote.by_month("2013-10")

如何实现?

现在我正在尝试:

ShiftNote.includes(:shift)
          .where("shifts.starts_at <= ? AND shifts.starts_at >= ?", "2013-10-01".to_date, "2013-10-30".to_date)

但我明白了

ShiftNote.includes(:shift).where("shifts.starts_at = ?", "2013-10-01".to_date, "2013-10-30".to_date) 弃用警告:看起来您急于加载表(一个 of: shift_notes, shifts) 在字符串 SQL 中引用 sn-p。例如:

Post.includes(:comments).where("comments.title = 'foo'")

目前,Active Record 识别字符串中的表,并且知道 将 cmets 表加入查询,而不是加载 cmets 在单独的查询中。然而,这样做没有写一个成熟的 SQL 解析器天生就有缺陷。因为我们不想写 SQL 解析器,我们正在删除此功能。从现在开始,你必须 当您从 字符串:

Post.includes(:comments).where("comments.title = 'foo'").references(:comments)

如果您不依赖隐式连接引用,您可以禁用 完全通过设置功能 config.active_record.disable_implicit_join_references = true。 SQL (1.6ms) SELECT shift_notes.id AS t0_r0, shift_notes.state AS t0_r1, shift_notes.user_id AS t0_r2, shift_days.shift_id AS t0_r3, shift_notes.created_at AS t0_r4, shift_notes.updated_at AS t0_r5, shifts.id AS t1_r0, shifts.starts_at AS t1_r1, shifts.ends_at AS t1_r2, shifts.rate AS t1_r3, shifts.limit AS t1_r4, shifts.created_at AS t1_r5, shifts.updated_at AS t1_r6, shifts.state AS t1_r7, shifts.shift_notes_count AS t1_r8 FROM shift_notes 左外 加入shifts ON shifts.id = shift_notes.shift_id 在哪里 (shifts.starts_at = '2013-10-30')

【问题讨论】:

  • ShiftNote.joins(:shift).where(shifts: { starts_at: ("2013-10-01".to_date.."2013-10-30".to_date) }) 应该这样做(从包含切换到连接,因为您正在连接/包含表上执行条件)

标签: mysql ruby-on-rails ruby date scope


【解决方案1】:

您可以使用BETWEEN 查询,这是使用日期范围实现的:

class ShiftNote < ActiveRecord::Base
  scope :by_month, ->(year = Date.today.year, month = Date.today.month) do
    first_day = Date.new(year, month, 1)
    last_day = Date.new(year, month + 1, 1) - 1
    joins(:shifts)
    .where('shifts.starts_at' => first_day..last_day)
  end

【讨论】:

  • 您需要将连接更改为 :shift
  • 我认为这不会是惯用的:)。不认真,ActiveRecord 从复数形式推断表的名称。
猜你喜欢
  • 1970-01-01
  • 2017-03-28
  • 2016-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-17
  • 2017-08-29
  • 1970-01-01
相关资源
最近更新 更多