【问题标题】:Active Record order by group sizeActive Record 按组大小排序
【发布时间】:2012-08-05 04:08:38
【问题描述】:

我有一个活动记录查询,我正在使用 group_by

@foo = Foo.group_by(&:relation)

然后在我正在使用的视图中

@foo.each do |group, values|
 group x has values.count elements
end

有没有办法按每个组的数量对这些进行排序?

【问题讨论】:

    标签: ruby ruby-on-rails-3 activerecord


    【解决方案1】:

    group_by 不是 ActiveRecord 方法,group 是。 group_by 是 Enumerator 方法。

    怎么样

    @foo = Foo.group('relation').order('count_id asc').count('id')
    

    取自"Order by" result of "group by" count?。

    否则,如果您想在 Ruby 级别对其进行排序,则可以这样做

    disordered_hash = {:two=>[1, 2], :one=>[1], :three=>[1, 2, 3]}
    ordered_array = disordered_hash.sort {|k, v| k[1].count <=> v[1].count} # add .reverse if you want
    # => [[:one, [1]], [:two, [1, 2]], [:three, [1, 2, 3]]]
    

    【讨论】:

    • #<0xc03dd68>
    • &gt;&gt;&gt;&gt;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-07
    • 1970-01-01
    • 2014-09-22
    • 2011-11-05
    • 2013-06-21
    • 2022-12-16
    • 2012-07-05
    相关资源
    最近更新 更多