【问题标题】:ActiveRecord order by a specific relations's valueActiveRecord 按特定关系的值排序
【发布时间】:2015-02-20 02:23:06
【问题描述】:
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 =&gt; 3

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

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

比如……

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

【问题讨论】:

  • 不清楚你想做什么。
  • 我有一个 :foos 的表。我希望能够根据每个 :foo 的最后一个 :bar 的值对它们进行排序。我很肯定范围会在某个地方工作,但我还没有弄清楚。我可以通过使用可枚举...Foo.all.sort_by(&amp;:some_method) 来实现我所追求的目标,其中some_method 正在计算最后一个:bar 的value。这样就清楚了吗?
  • 我的问题是,可枚举很慢...
  • 做了类似的帮助 -- stackoverflow.com/questions/9197649/…

标签: mysql sql ruby-on-rails ruby activerecord


【解决方案1】:
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'。

干杯!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多