Sort by aggregate or calculated column added to model

I wanna sort by ISO3166::Country.find_country_by_alpha2(:country) where the :country column in my database contains the alpha2 so I created a function in my model and tried to use it in my controller order clause but it didn’t work Can someone please correct my syntax

model: def country_iso_short_name ISO3166::Country.find_country_by_alpha2(:country) end

controller: @festivals = Festival.all.order(:country_iso_short_name, :state, :name)

As far as I understand, your country_iso_short_name is not stored in the database, it is just a method.

If that is the case, that could be the error…

The order method, asks the database to order the record, but you don’t have that column in your database.

So I have two options two solve the problem:

  1. You can save that value on your database
  2. Or you can use sort_by

Save the value on the database

To do that you will need to…

  • Add the column to your database
  • Update the value when the record changes (You could do that on a before_save callback…)
class Festival < ApplicationRecord
  before_save do
    self.country_iso_short_name = ISO3166::Country.find_country_by_alpha2(country) 
  end
end

Use sort_by

Sort by is a method from then Enumerable module, so it will sort the collection using ruby. So, you won’t need to add the column to the database.