【问题标题】:How to order the same set of records two times, the second ordering performing independently from the first one?如何对同一组记录进行两次排序,第二次排序独立于第一次执行?
【发布时间】:2014-10-19 14:57:20
【问题描述】:

我需要创建一种演绎查询,其中相同的记录被多次排序,并且每次的排序都独立于之前的订单执行。

如:

tallest_trees = Trees.order(:height => :desc).limit(10) # Gets 10 of the tallest trees out of all available trees
tallest_trees.order(:width => :desc) # From the 10 of the tallest trees, gets the widest trees **without** any regard to their height

我尝试以与上述类似的方式进行操作,但结果始终是它尝试在本例中按高度和宽度对树木进行排序同时,这与我的需求相反。

在直接使用 ActiveRecord 或 SQL 方面没有任何区别。我相信答案是我必须以某种方式“稳定”上一个查询,以便第二个查询不仅继续它,而且重新排序。

【问题讨论】:

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


    【解决方案1】:

    有两种方法。第一:

    base_scope = Trees.limit(10)
    tallest_trees = base_scope.order(height: :desc)
    widest_trees = base_scope.order(width: :desc)
    

    第二个 - 使用reorder 方法:

    tallest_trees = Trees.order(height: :desc).limit(10)
    widest_trees = tallest_trees.reorder(width: :desc)
    

    【讨论】:

    • reorder 就是这样!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-06
    相关资源
    最近更新 更多