I have to order an ActiveRecord Relation.
Profile.where(id: [1,2,3]).order_user_preferences
where records with country_code = 'US' (or a specific string) first. I've created this self.order_user_preferences, but I can't access the relation object inside the method. I think "sort_by" converts the ActiveRecord Relation to an array. Do you know how to keep it as an "Active record relation"?
class Profile
def self.order_user_preferences()
# Order by user country
countries = ['US']
# User-country first
return relation.sort_by {|p| countries.include?(p.country_code) ? 0 : 1} if countries.size > 0
end
end
Expected results
PROFILE ID | Country code
1 | US
2 | EU
3 | JP