1

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"
2
  • Why do you have string values that are actually numbers in first place? Commented Jul 8, 2012 at 17:40
  • @ismaelga I'm still learning. I've got many other strings and these are number values to them. For instance I've got :word_one, :word_two, :word_three -- these are the numbers that go along with them without creating overgrown tables in the db. Commented Jul 8, 2012 at 17:44

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Can you give me an example? I appreciate it! I can't seem to figure out the second ActiveRecord example inside my controller action. My controller action looks like this: @ethos = user.ethos

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.