gpt4 book ai didi

mysql - ActiveRecord 按特定关系的值排序

转载 作者:行者123 更新时间:2023-11-29 00:03:28 25 4
gpt4 key购买 nike

class Foo < ActiveRecord::Base
has_many :bar
end

class Bar < ActiveRecord::Base
belongs_to :foo
end

我想根据它的最后一个 :bar 来订购我的 :foos...

那么,让我们说:

Foo.first.bars => [{key: 'a', value: 1}, {key: 'b', value: 2}, {key: 'c', value: 3}]

所以... Foo.first.bars.last.value => 3

我有一堆 :foos,每个都有一堆 :bars,但我只关心最后一个 :bar。

我可以根据 :foos 的最后一个 :bars value 对我的 :foos 进行排序吗? Bar 需要范围吗?

例如...

Foo.includes(:bars).order('bars.last.value')

最佳答案

class Foo < ActiveRecord::Base
has_many :bar
scope :latest_foo_value, ->(ord) { includes(:foos).order("foos.value #{ord.upcase}") }
end

class Bar < ActiveRecord::Base
belongs_to :foo
default_scope order: 'created_at DESC'
end

谢谢@Doon!如果您想将其复制并粘贴到您自己的答案中,我很乐意给予您信任。你知道是否有办法在 Bar 上调用命名范围?像这样的东西:

class Foo < ActiveRecord::Base
has_many :bar
scope :latest_foo_value, ->(ord) { includes(:foos).order("foos.current.value #{ord.upcase}") }
end

class Bar < ActiveRecord::Base
belongs_to :foo
scope :current, -> { order('created_at DESC') }
end

那行不通... Mysql2::Error: Unknown column 'foos.current.value' in 'order clause'

干杯!

关于mysql - ActiveRecord 按特定关系的值排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28620659/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com