Ruby on rails 如何对同一组记录进行两次排序,第二次排序独立于第一次排序?
我需要创建一种演绎查询,在这种查询中,相同的记录被多次排序,并且每次排序都是独立于以前的订单执行的 例如:Ruby on rails 如何对同一组记录进行两次排序,第二次排序独立于第一次排序?,ruby-on-rails,activerecord,ruby-on-rails-4,Ruby On Rails,Activerecord,Ruby On Rails 4,我需要创建一种演绎查询,在这种查询中,相同的记录被多次排序,并且每次排序都是独立于以前的订单执行的 例如: 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, get
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没有任何区别。我相信答案是,我必须以某种方式稳定前一个查询,以便第二个查询不只是继续,而是重新排序。有两种方法。第一:
base_scope = Trees.limit(10)
tallest_trees = base_scope.order(height: :desc)
widest_trees = base_scope.order(width: :desc)
第二种方法:
重新排序就这样!谢谢
tallest_trees = Trees.order(height: :desc).limit(10)
widest_trees = tallest_trees.reorder(width: :desc)