【发布时间】:2021-08-31 19:58:30
【问题描述】:
对活动记录非常陌生。
我正在尝试使用活动记录来查询“更改”并按其孩子(ctasks 和 legacy_ctasks)最近的 start_time 对其进行排序。
如果变更有 ctasks 和 legacy_ctasks,排序时使用最早(最小)的 start_time。
一项更改必须至少有一个 ctask 或 legacy_ctask。
一个变更可以有很多 ctasks 和/或很多 legacy_ctasks
ctasks 和 legacy_ctasks 都有一个 start_time 字段:
t.datetime "start_time":
型号:
class Change < ApplicationRecord
has_many :ctasks, -> { order "start_time ASC" }, dependent: :destroy
has_many :legacy_ctasks, -> { order "start_time ASC" }, dependent: :destroy
end
class LegacyCtask < ApplicationRecord
belongs_to :change, touch: true
end
class Ctask < ApplicationRecord
belongs_to :change, touch: true
end
我目前的尝试非常悲伤:
Change.left_joins(:ctasks, :legacy_ctasks).order('ctasks.start_time ASC').order('legacy_ctasks.start_time ASC').distinct
【问题讨论】:
标签: ruby-on-rails activerecord