简体   繁体   English

Rails 4 ActiveRecord的关联计数顺序

[英]Rails 4 ActiveRecord order by count of association

There's a view where I want to display the contents of 我要在其中显示内容的视图

for example: 例如:

recipe.user.name 
recipe.name
recipe.picture
recipe.created_at

sorted by 排序

recipe.likes.count

Controller: 控制器:

@recipes_by_likes = Recipe.likes_count.paginate(page: params[:page])

Model: 模型:

Recipe has_many :likes

and

Like belongs_to :recipe

Scope: 范围:

scope :likes_count, -> { 
  select('recipes.*, COUNT(likes.id) AS likes_count').
  joins(:likes).
  order('likes_count DESC')
}

but that gives me 但这给了我

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

which returns only 1 (wrong) result. 仅返回1(错误)结果。

1. Query 1.查询

You should not count likes by their id since it is always unique and will always return 1, instead by the recipe_id which is the same in the likes associated with a certain recipe. 您不应该按喜欢的id计算喜欢数,因为它始终是唯一的,并且总是返回1,而不要使用与特定食谱相关的喜欢中相同的recipe_id

scope :likes_count, -> { 
  select('recipes.*, COUNT(likes.recipe_id) AS likes_count')
  .joins(:likes)
  .group('recipes.id')
  .order('likes_count DESC')
}

2. Counter Cache Method 2.计数器缓存方法

Also you can use a counter_cache 你也可以使用counter_cache

class Like < ActiveRecord::Base
  belongs_to :recipe, counter_cache: true
end

And add a column to Recipe model 并在Recipe模型中添加一列

add_column :recipes, :likes_count, :integer, default: 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM