如何从belongs_to关联模型中定义by_month?

时间:2013-10-21 13:55:41

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

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)SELECT shift_notesid AS t0_r0,shift_notesstate AS   t0_r1,shift_notesuser_id AS t0_r2,shift_daysshift_id AS   t0_r3,shift_notescreated_at AS t0_r4,shift_notesupdated_at   AS t0_r5,shiftsid AS t1_r0,shiftsstarts_at AS t1_r1,   shiftsends_at AS t1_r2,shiftsrate AS t1_r3,   shiftslimit AS t1_r4,shiftscreated_at AS t1_r5,   shiftsupdated_at AS t1_r6,shiftsstate AS t1_r7,   shiftsshift_notes_count AS t1_r8 FROM shift_notes LEFT OUTER   加入shifts shiftsid = shift_notesshift_id WHERE   (shifting.starts_at&lt; =''2013-10-01'AND shift.starts_at&gt; =   '二零一三年十月三十零日')

1 个答案:

答案 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