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(“shifting.starts_at&lt; =?AND shifting.starts_at&gt; =?”,“2013-10-01”.to_date,“2013-10-30”.to_date ) 弃权警告:看起来你急于装桌子(一个 of:shift_notes,shifting)在字符串SQL中引用 片段。例如:
Post.includes(:comments).where("comments.title = 'foo'")
目前,Active Record识别字符串中的表,并且知道 将评论表加入查询,而不是加载评论 在单独的查询中。然而,这样做没有写完全 SQL解析器本质上是有缺陷的。因为我们不想写SQL 解析器,我们正在删除此功能。从现在开始,你必须 当您从a引用表时,显式地告诉Active Record 字符串:
Post.includes(:comments).where("comments.title = 'foo'").references(:comments)
如果您不依赖隐式连接引用,则可以禁用 功能完全由设置
config.active_record.disable_implicit_join_references = true
。 SQL (1.6ms)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_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 FROMshift_notes
LEFT OUTER 加入shifts
shifts
。id
=shift_notes
。shift_id
WHERE (shifting.starts_at&lt; =''2013-10-01'AND shift.starts_at&gt; = '二零一三年十月三十零日')
答案 0 :(得分: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