我遇到了一个问题,我必须根据job_trade_contractors的min time_out字段对工作进行排序。对于job_trade_contractors,time_out字段可能为零。我有类似的关联:
1:job.rb
has_many :job_trades, dependent: :destroy
has_many :job_trade_contractors, through: :job_trades
2:job_trade.rb
has_many :job_trade_contractors, dependent: :destroy
3:job_trade_contractors.rb
belongs_to :job_trade, touch: true
当前,我正在通过以下代码对作业进行排序:
Job.left_joins(:job_trade_contractors).order("job_trade_contractors.time_out asc")
它可以根据time_out正确地对作业进行排序,但我需要的是对job_trade_contractors属于特定作业的最小time_out值进行排序。
假设我们有2个工作,每个工作有5个job_trade_contractors。我们将需要根据关联的job_trade_contractors中的最小time_out值对作业进行排序。
示例 职位
j1 ->
1: job_trade_contractor ->
id: 1
time_out: 21-01-2020
2: job_trade_contractor ->
id: 2
time_out: 20-01-2020
3: job_trade_contractor ->
id: 3
time_out: 11-01-2020
4: job_trade_contractor ->
id: 4
time_out: 19-01-2020
5: job_trade_contractor ->
id: 5
time_out: 23-01-2020
j2 ->
1: job_trade_contractor ->
id: 1
time_out: 21-01-2020
2: job_trade_contractor ->
id: 2
time_out: 20-01-2020
3: job_trade_contractor ->
id: 3
time_out: 11-01-2020
4: job_trade_contractor ->
id: 4
time_out: 10-01-2020
5: job_trade_contractor ->
id: 5
time_out: 25-01-2020
结果应为
j2 j1
因为我们的job_trade_contractor的time_out值是:j2中的min_time为10-01-2020 和11年1月11日在j1
答案 0 :(得分:0)
我们可以通过以下方式实现排序,这可能对您有所帮助
has_many :job_trade_contractors, through: :job_trades, order: 'job_trade_contractors.time_out'
或
has_many :job_trade_contractors, -> { order(time_out: :asc) }, through: :job_trades
答案 1 :(得分:0)
您可以尝试
Job.joins(job_trades: :job_trade_contractors).order('job_trade_contractors.time_out').uniq