[英]How to scope by_month from belongs_to associated model?
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 <=?AND shifts.starts_at> =?”,“ 2013-10-01” .to_date,“ 2013-10-30” .to_date)声明警告:它看起来您很想加载在字符串SQL代码段中引用的表(其中一个:shift_notes,shifts)。 例如:
Post.includes(:comments).where("comments.title = 'foo'")
当前,Active Record可以识别字符串中的表,并且知道将注释表加入查询中,而不是在单独的查询中加载注释。 但是,在不编写成熟的SQL解析器的情况下执行此操作本质上是有缺陷的。 由于我们不想编写SQL解析器,因此我们将删除此功能。 从现在开始,当您从字符串引用表时,必须显式告知Active Record:
Post.includes(:comments).where("comments.title = 'foo'").references(:comments)
如果您不依赖隐式联接引用,则可以通过设置
config.active_record.disable_implicit_join_references = true
完全禁用该功能。 SQL(1.6毫秒)SELECTshift_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_r3shifts
。limit
AS t1_r4,shifts
。created_at
AS t1_r5,shifts
。updated_at
AS t1_r6,shifts
。state
AS t1_r7shifts
。shift_notes_count
AS t1_r8 FROMshift_notes
LEFT OUTER JOINshifts
ONshifts
。id
=shift_notes
。shift_id
哪里(shifts.starts_at <='2013-10-01'AND shifts.starts_at> ='2013-10-30')
您可以使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.