我想要显示
的内容例如:
recipe.user.name
recipe.name
recipe.picture
recipe.created_at
按
排序recipe.likes.count
控制器:
@recipes_by_likes = Recipe.likes_count.paginate(page: params[:page])
型号:
Recipe has_many :likes
和
Like belongs_to :recipe
范围:
scope :likes_count, -> {
select('recipes.*, COUNT(likes.id) AS likes_count').
joins(:likes).
order('likes_count DESC')
}
但是这给了我
SELECT recipes.*, COUNT(likes.id) AS likes_count
FROM "recipes"
INNER JOIN "likes" ON "likes"."recipe_id" = "recipes"."id"
ORDER BY "recipes"."created_at" DESC, likes_count DESC
LIMIT 30 OFFSET 0
只返回1(错误)结果。
答案 0 :(得分:2)
你不应该按照document.getElementsByClassName(name)
计算喜欢,因为它总是唯一的,并且总是返回1,而不是id
,这与某个食谱相关的喜欢相同。
recipe_id
您也可以使用scope :likes_count, -> {
select('recipes.*, COUNT(likes.recipe_id) AS likes_count')
.joins(:likes)
.group('recipes.id')
.order('likes_count DESC')
}
counter_cache
并向class Like < ActiveRecord::Base
belongs_to :recipe, counter_cache: true
end
模型
Recipe