[英]rails sort_by method in descending and offset limit
我只是想知道在我調用sort_by total_like方法之后,通過在自定義方法欄中遞減來進行偏移量限制和排序。 這是我在模型中的自定義方法
class Post < ApplicationRecord
def total_like
self.likeposts.count
end
... more code ...
這是腳本,當我嘗試調用按total_like降序排列的帖子時
if POST==@current_entity
@entities=[]
@entity.where(paramshash).sort_by(&:total_like).reverse!.each.with_index do |entity, index|
if index >= params[:offset].to_i && index <= params[:offset].to_i + params[:limit].to_i
@entities << entity
end
end
render json: @entities
任何人都可以簡單地做到這一點,不需要調用我的Post表中的所有記錄:(
我認為這樣可能有效:
Post
.joins(:likeposts)
.group('posts.id')
.order('COUNT(likeposts.id) DESC')
.offset(params[:offset])
.limit(params[:limit])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.