用户点赞:products Products has_many :likes
我想根据用户获得的总点赞数按降序返回记录。
例如,用户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
执行此操作的最有效方法是什么?
发布于 2011-11-01 14:06:53
我们必须在这里使用计数器缓存来跟踪每个产品的点赞数量。为此,我们需要将integer类型的新列likes_count添加到products表中。
参考:http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
用户模型:
class User < ActiveRecord::Base
has_many :products
scope :popular_products, joins(:products).group("user_id").
order("sum(likes_count) DESC")
end产品型号:
class Product < ActiveRecord::Base
belongs_to :user
has_many :likes
endLike模型:
class Like < ActiveRecord::Base
belongs_to :product , :counter_cache => true
endhttps://stackoverflow.com/questions/7962414
复制相似问题