SQLite、Ruby on Rails.如何使用 act_as_votable gem 获得最高投票对象? [英] SQLite, Ruby on rails. How to get the top voted objects with acts_as_votable gem?
问题描述
我正在尝试显示过去 7 天内最好的 3 个食谱.最好的方法取决于它使用acts_as_votable gem 获得的票数,但我还没有创建缓存.当前用户.rb,限制为过去 7 天
I"m trying to display the best 3 Recipes from the last 7 days. The best is dependant on the amount of votes it has using the acts_as_votable gem but i have not created a cache. current user.rb, limits to the last 7 days
def featuredfeed
Recipe.where('created_at >= ?', Time.zone.now - 1.week)
end
食谱.rb
class Recipe < ActiveRecord::Base
belongs_to :user
acts_as_votable
....
default_scope -> { 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,需要计算它被点赞的次数
The votable_id is the id of the recipe which needs to be counted for the number of times it has been upvoted
推荐答案
我想说,缓存投票是比下面一个更简洁的解决方案.这只是添加新迁移的问题.但取决于你..
I would like to say, that caching votes is much cleaner solution, than the following one. It is just a matter of adding a new migration. But up to you..
获取最近食谱的 id(这部分你已经完成了):
Get the ids of recent recipes (this part you already have done):
recipes_ids = Recipe.where('created_at >= ?', Time.zone.now - 1.week)
过滤此食谱的投票:
Vote
.where(votable_id: recipes_ids)
按 votable_id
将它们分组:
.group(:votable_id)
并找到那些拥有更多票的人,至少有 1 票:
And find those, which have more, at least 1 vote:
.having('count(votable_id) > 1')
现在获取 3 个最受好评的食谱的 ID:
Now take the ids of 3 most upvoted recipes:
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)
最后,找到那些最受欢迎的食谱:
And, lastly, find those most popular recipes:
most_popular_recipes = Recipe.where(id: most_voted_recipes_ids)
这篇关于SQLite、Ruby on Rails.如何使用 act_as_votable gem 获得最高投票对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!