简体   繁体   中英

How to scope by_month from belongs_to associated model?

ShiftNote belongs_to Shift has_many ShiftNote

I want to have scope ShiftNote.by_month("2013-10")

How to implement that?

Right now I am trying:

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

But I get

ShiftNote.includes(:shift).where("shifts.starts_at <= ? AND shifts.starts_at >= ?", "2013-10-01".to_date, "2013-10-30".to_date) DEPRECATION WARNING: It looks like you are eager loading table(s) (one of: shift_notes, shifts) that are referenced in a string SQL snippet. For example:

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

Currently, Active Record recognizes the table in the string, and knows to JOIN the comments table to the query, rather than loading comments in a separate query. However, doing this without writing a full-blown SQL parser is inherently flawed. Since we don't want to write an SQL parser, we are removing this functionality. From now on, you must explicitly tell Active Record when you are referencing a table from a string:

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

If you don't rely on implicit join references you can disable the feature entirely by setting 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 LEFT OUTER JOIN shifts ON shifts . id = shift_notes . shift_id WHERE (shifts.starts_at <= '2013-10-01' AND shifts.starts_at >= '2013-10-30')

You can use a BETWEEN query, which is achieved using a range of dates:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM