SQLite,Ruby on rails。 如何使用acts_as_votable gem获取最高投票对象?
我试图显示过去7天内最好的3个食谱。最好的是取决于使用acts_as_votable gem的投票数量,但我还没有创建缓存。当前user.rb,过去7天的限制
def featuredfeed Recipe.where('created_at >= ?', Time.zone.now - 1.week) end
recipe.rb
class Recipe { order(created_at: :desc) } end
投票表是订购的
id, votable_id, votable_type, voter_id, voter_type, vote_flag, vote_scope, vote_weight, created_at, updated_at
votable_id是食谱的id,需要计算其被投票的次数
我想说,缓存投票比下一个更清晰。 这只是添加新迁移的问题。 但取决于你..
获取最近食谱的ID(这部分你已经完成了):
recipes_ids = Recipe.where('created_at >= ?', Time.zone.now - 1.week)
过滤此食谱的投票:
Vote .where(votable_id: recipes_ids)
通过votable_id
它们进行votable_id
:
.group(:votable_id)
并找到那些有更多,至少1票的人:
.having('count(votable_id) > 1')
现在拿3个最受欢迎的食谱的ID:
most_voted_recipes_ids = Vote .where(votable_id: recipes_ids) .group(:votable_id) .having('count(votable_id) > 1') .limit(3).votable_ids # or limit(3).pluck(:votable_id)
最后,找到最受欢迎的食谱:
most_popular_recipes = Recipe.where(id: most_voted_recipes_ids)