使用自定义方法订购 Active Record 关系

Order an Active Record Relation with a custom method

我必须订购 ActiveRecord 关系。

Profile.where(id: [1,2,3]).order_user_preferences

where 以 country_code = 'US'(或特定字符串)开头的记录。 我已经创建了这个 self.order_user_preferences,但我无法访问方法内的关系对象。 我认为“sort_by”将 ActiveRecord 关系转换为数组。你知道如何将其保存为“活动记录关系”吗?

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 

预期结果

个人资料 ID |国家代码

1 |美国

2 |欧盟

3 |日本

您需要 order 而不是 sort_by。按可枚举对象的排序排序,它不知道关联。在这里阅读更多:https://apidock.com/ruby/Enumerable/sort_by

所以你可能会得到类似 Profile.joins(:countries).where(id: [1,2,3], countries: {country_code: "US"}).order("countries.country_code asc")

的结果

这将为您带来 ID 为 1 或 2 或 3 且它们具有与国家相关联的国家/地区的任何配置文件。没有关联国家/地区的配置文件将不包括在内。