0

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

sparkle
  • 7,530
  • 22
  • 69
  • 131

1 Answers1

0

You need order not sort_by. Sort by sort on the enumerable object and it is not aware of associations. Read more here: https://apidock.com/ruby/Enumerable/sort_by

So you will probably end up with something like Profile.joins(:countries).where(id: [1,2,3], countries: {country_code: "US"}).order("countries.country_code asc")

This will bring you any profiles where the id is 1 or 2 or 3 and they HAVE an associated country with country. Profiles that do not have an associated country will not be included.

Tashows
  • 545
  • 6
  • 21
  • I need to put profiles with country_code = US first, then other countries'. It's not a where condition. – sparkle Feb 01 '21 at 15:54
  • 1
    Oh I see. Check this answer: https://stackoverflow.com/questions/17637983/order-alphabetically-but-with-one-value-at-the-top – Tashows Feb 01 '21 at 16:09