Ruby on rails 嵌套顺序、组、计数和的最有效方式?

Ruby on rails 嵌套顺序、组、计数和的最有效方式?,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,用户有很多:产品 产品有很多:喜欢 我想根据用户得到的喜欢的总数,按降序返回用户的记录 e、 g。 用户1拥有产品(A、B、C) A=4喜欢,B=2喜欢,C=1喜欢,总计=7喜欢 用户2拥有产品(D、E) D=4个喜欢,E=6个喜欢,总计=10个喜欢 用户3拥有产品(F、G、H、I) F、 G,H,I=每1个喜欢,总计=4个喜欢 结果=>用户2、用户1、用户3 最有效的方法是什么?我们必须在这里使用计数器缓存来跟踪每个产品的同类数量。为此,我们需要在products表中添加一个新列,如integ

用户有很多:产品 产品有很多:喜欢

我想根据用户得到的喜欢的总数,按降序返回用户的记录

e、 g。 用户1拥有产品(A、B、C) A=4喜欢,B=2喜欢,C=1喜欢,总计=7喜欢

用户2拥有产品(D、E) D=4个喜欢,E=6个喜欢,总计=10个喜欢

用户3拥有产品(F、G、H、I) F、 G,H,I=每1个喜欢,总计=4个喜欢

结果=>用户2、用户1、用户3


最有效的方法是什么?

我们必须在这里使用计数器缓存来跟踪每个产品的同类数量。为此,我们需要在products表中添加一个新列,如integer类型的\u count

参考:

用户模型:

class User < ActiveRecord::Base
 has_many :products
 scope :popular_products, joins(:products).group("user_id").
        order("sum(likes_count) DESC")
end
class用户
产品型号:

class Product < ActiveRecord::Base
  belongs_to :user
  has_many :likes
end
类产品
类似模型:

class Like < ActiveRecord::Base
  belongs_to :product , :counter_cache => true
end
类类似于true
结束

我们必须在这里使用计数器缓存来跟踪每个产品的同类数量。为此,我们需要在products表中添加一个新列,如integer类型的\u count

参考:

用户模型:

class User < ActiveRecord::Base
 has_many :products
 scope :popular_products, joins(:products).group("user_id").
        order("sum(likes_count) DESC")
end
class用户
产品型号:

class Product < ActiveRecord::Base
  belongs_to :user
  has_many :likes
end
类产品
类似模型:

class Like < ActiveRecord::Base
  belongs_to :product , :counter_cache => true
end
类类似于true
结束