Patrick A.
Patrick A.

Reputation: 103

Rails 3: Sorting by many strings

I have multiple strings that are all number values. They are all inside the same db table. Is there a way to join them all and sort by the highest number?

Something like (pseudo code):

:include => :word_one_value, :word_two_value, :word_three_value, :sort_by => "sum ASC"

Upvotes: 1

Views: 105

Answers (1)

Mori
Mori

Reputation: 27789

In MySql:

Foo.order '(convert(word_one, unsigned) +
            convert(word_two, unsigned) +
            convert(word_three, unsigned))'

In ActiveRecord:

Foo.all.sort_by do |f| 
  %w[one two three].sum { |n| f.send("word_#{n}").to_i } 
end

Or if these fields are inside Foo:

class Foo < ActiveRecord::Base
    def self.sorted_by_sum_of_words
      order '(convert(word_one, unsigned) +
              convert(word_two, unsigned) +
              convert(word_three, unsigned))'
    end
end

Then in the controller:

class FooController < ApplicationController
  def my_action
    @foos = Foo.sorted_by_sum_of_words        
  end
end

The conversions are unnecessary if you store numbers in number columns.

Upvotes: 1

Related Questions