ruby 如何按类型和created_at筛选has_many记录?

snz8szmq  于 2023-06-22  发布在  Ruby
关注(0)|答案(1)|浏览(111)

(以Ruby/Rails初学者的身份提问)
一个组有许多音符。Notes有一个type_id。
如果type_id存在,我想通过type_id过滤组中的注解,但也要过滤created_at最早的地方。
模式1:如果type_id存在
如果今天写了两个相同类型的笔记,抓住它们。
如果两个相同类型的笔记是在不同的日子写的,则获取最新的/最近的。
模式2:如果type_id不存在
抓取所有笔记
按类型仅选择最近的注解。
如果在不同的日期存在相同类型的注解,则将其过滤掉。
我能够得到模式1(虽然相当脏?我需要打两次电话)

if params[:note_type_id].present?
  earliest_date = note
                  .where(notes_type_id: params[:notes_type_id])
                  .minimum(:created_at)
  notes
    .where(notes_type_id: params[:notes_type_id])
    .where(created_at: earliest_date.all_day)

我不知道如何开始模式2。我在想不要在数据库端这样做,而只是使用ruby来过滤。
所有的建议赞赏。

py49o6xq

py49o6xq1#

模式1:如果type_id存在
如果今天写了两个相同类型的笔记,抓住它们。

notes_of_type = note.where(notes_type_id: params[:notes_type_id])

notes_today = notes_of_type
  .where(created_at: Date.today.all_day)
  .limit(2) # ?? Ambiguous question -- did you mean to only get a maximum of 2, or "all of them"?

如果两个相同类型的笔记是在不同的日子写的,抓住最早/最近的。
“最早”和“最近”的意思正好相反。我想你是指最近的。
在这种情况下,你可以这样做:

if notes_today.none?
  notes_of_type.order(created_at: :desc).first
end

模式2:如果type_id不存在
抓取所有笔记
按类型仅选择最近的注解。
如果在不同的日期存在相同类型的注解,则将其过滤掉。
最后一个要求对我来说是多余的。如果我们只按类型选择最近的笔记,那么就不需要额外的过滤了吗?
有几种方法。下面是一个通用的策略,使用窗口函数

select_sql = Note.select('*, dense_rank() OVER (PARTITION BY notes_type_id ORDER BY created_at desc) as recent_rank')

Note.from(select_sql, 'notes').where(recent_rank: 1) # Or get the "2 most recent"

相关问题