How do I sort in ruby/rails on two fields?
The best way would be to have your database do it, but if you want to use Ruby:
@games = @data.sort_by {|x| [x.game_date, x.team] }
The sorting behaviour of Array
is to sort by the first member, then the second, then the third, and so on. Since you want the date as your primary key and the team as the second, an array of those two will sort the way you want.
Ruby on Rails: how do I sort with two columns using ActiveRecord?
Assuming you're using MySQL,
Model.all(:order => 'DATE(updated_at), price')
Note the distinction from the other answers. The updated_at
column will be a full timestamp, so if you want to sort based on the day it was updated, you need to use a function to get just the date part from the timestamp. In MySQL, that is DATE()
.
Rails Sort Array By Two Columns
Use sort_by:
surveys.sort_by { |survey| [survey.length, survey.cost] }
If you want to control asc vs desc, just multiply by -1:
surveys.sort_by { |survey| [-1 * survey.length, survey.cost] }
This should work for both regular array of objects or ActiveRecord::Relation
ruby sort_by multiple fields
Your sorting works correctly in MRI Ruby 1.8.7, 1.9.3, and 2.0.0:
Item = Struct.new(:name, :dir, :sort_dir)
entries = [Item.new('favicon.ico', false, 1), Item.new('bin', true, 0),
Item.new('web.config', false, 1), Item.new('images', true, 0),
Item.new('global.asax', false, 1), Item.new('content', true, 0)]
entries.sort_by{|e| [e.sort_dir, e.name]}
# => [#<struct Item name="bin", dir=true, sort_dir=0>,
# #<struct Item name="content", dir=true, sort_dir=0>,
# #<struct Item name="images", dir=true, sort_dir=0>,
# #<struct Item name="favicon.ico", dir=false, sort_dir=1>,
# #<struct Item name="global.asax", dir=false, sort_dir=1>,
# #<struct Item name="web.config", dir=false, sort_dir=1>]
Have you tried outputting the result of your sort_by
to a console? I'm not familiar with the render json:
portion of your code, but perhaps that's where things are going wrong. My best guess is that somehow in the conversion to JSON (if that's what it does) the sorting is getting messed up.
My other idea is that perhaps you expect sort_by
to modify entries
; it does not. If you want entries
itself to be sorted after the call, use sort_by!
(note the !
at the end of the method name).
Update: It looks like the issue is that you want a case-insensitive search. Simply adding upcase
should do the trick:
entries.sort_by{|e| [e.sort_dir, e.name.upcase]}
Rails sort_by method with two fields one sorted ascending, one sorted descending
You question has nothing to do with rendering partials. what you are interested in is the behaviour of sort_by method .
In btw, this should solve your problem:
<%= render @players.sort_by { |p| [-p.scored_vote(current_week), p.last_name] } %>
Ruby sort by multiple fields and multilple directions for different data types
Very interesting problem. I also think the sort_by
method would be most helpful.
My solution (for numerical values only) works like this:
DIRECTION_MULTIPLIER = { asc: 1, desc: -1 }
def multi_sort(items, order)
items.sort_by do |item|
order.collect do |key, direction|
item[key]*DIRECTION_MULTIPLIER[direction]
end
end
end
# ... items ...
multi_sort(items, a_sort: :asc, display_sort: :desc)
The idea is to construct a list for each item passed by sort_by
. This list consists out of all values for which a sort order was given. Hence, we use that Ruby knows that [1,2]
is smaller than [1,3]
but greater than [0,0]
.
An interesting part to note is that the last parameters for the function will be passed as one Hash and the order of these hash pairs will be maintained. This "ordered" behavior in Hashes is not necessarily true for all languages, but the Ruby documentation states: Hashes enumerate their values in the order that the corresponding keys were inserted
.
-- Edit for more generality --
Since, chamnap asked for a more general solution which works with arbitrary data types and nil
, here a more comprehensive solution which relies on the <=>
operator:
require 'date'
DIRECTION_MULTIPLIER = { asc: 1, desc: -1 }
# Note: nil will be sorted towards the bottom (regardless if :asc or :desc)
def multi_sort(items, order)
items.sort do |this, that|
order.reduce(0) do |diff, order|
next diff if diff != 0 # this and that have differed at an earlier order entry
key, direction = order
# deal with nil cases
next 0 if this[key].nil? && that[key].nil?
next 1 if this[key].nil?
next -1 if that[key].nil?
# do the actual comparison
comparison = this[key] <=> that[key]
next comparison * DIRECTION_MULTIPLIER[direction]
end
end
end
I am using the sort
method. The block gets called each time the sort function needs to compare to elements. The block shall return -1, 0 or 1 (smaller, equal or higher in the order) for the respective pair. Within this sort block I am going through the order
hash which contains the key and the direction for a hash value in items. If we have found an earlier difference in order (e.g. the first key was higher) we just return that value. If the past comparisons came up with equal order, we use the <=>
operator to compare the two elements passed to the sort block (and multiply the result it with -1 if we want descending order). The only annoying thing is to deal with nil
values, which adds the three lines above the actual comparison.
And here my test code:
items = [ {n: 'ABC ', a: 1, b: Date.today+2},
{n: 'Huhu ', a: nil, b: Date.today-1},
{n: 'Man ', a: nil, b: Date.today},
{n: 'Woman', a: nil, b: Date.today},
{n: 'DEF ', a: 7, b: Date.today-1}]
multi_sort(items, b: :asc, a: :desc, n: :asc)
On a more general note: Since the logic for sorting becomes a little more complicated, I would wrap the data in actual objects with attributes. Then you could overwrite the <=>
operator as seen here.
Multiple field sort_by combination of reverse and not
data = [{:score=>100.0, :matches_count=>2, :name=>"DAV"},
{:score=>100.0, :matches_count=>1, :name=>"SAN"},
{:score=>100.0, :matches_count=>1, :name=>"PAS"},
{:score=>110.0, :matches_count=>1, :name=>"PAR"},
{:score=>100.0, :matches_count=>1, :name=>"NUE"}]
data.sort_by{ |h| [-h[:score], -h[:matches_count], h[:name]] }
#=> [{:score=>110.0, :matches_count=>1, :name=>"PAR"},
# {:score=>100.0, :matches_count=>2, :name=>"DAV"},
# {:score=>100.0, :matches_count=>1, :name=>"NUE"},
# {:score=>100.0, :matches_count=>1, :name=>"PAS"},
# {:score=>100.0, :matches_count=>1, :name=>"SAN"}]
You could also use Array#sort, which does not require that values to be sorted on in descending order be numeric, so long as they are comparable, that is, so long as they respond to the method :<=>
.
data.sort do |t1, t2|
case t1[:score] <=> t2[:score]
when -1
1
when 1
-1
else
case t1[:matches_count] <=> t2[:matches_count]
when -1
1
when 1
-1
else
t1[:name] <=> t2[:name]
end
end
end
#=> <as above>
How to sort based on two fields
You can try with coalesce
:
Product.order('coalesce(sale_price, price)')
Related Topics
How to Include Variables in My Vagrantfile
Ruby: Character to Ascii from a String
What Is the Best/How to Validate an Email Address in Ruby
Rebase Rails Migrations in a Long Running Project
Ruby Methods and Optional Parameters
Form Submitted Twice, Due to :Remote=>True
Bundler Could Not Find Compatible Versions for Gem "Bundler":
How to Replace the Unicode Gem on Ruby 1.9
Failed to Build Gem Native Extension
Difference Between Kernel#Yield_Self, Yield(Self), Kernel#Then and Object#Tap in Ruby
Prepend a Single Line to File with Ruby
Are Rails Controllers Multithreaded? Thread.Exclusive in Controllers
How to Deal with Not Knowing What Exceptions Can Be Raised by a Library Method in Ruby