简体   繁体   English

rails sort_by方法的下降和偏移量限制

[英]rails sort_by method in descending and offset limit

i just wondering do offset limit and ordering by descending in my custom method rails after i called sort_by total_like method. 我只是想知道在我调用sort_by total_like方法之后,通过在自定义方法栏中递减来进行偏移量限制和排序。 this is my custom method in model 这是我在模型中的自定义方法

 class Post < ApplicationRecord
 def total_like
    self.likeposts.count
 end
 ... more code ...

and this is script when i tried to calling post that sort by total_like in descending 这是脚本,当我尝试调用按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

can anyone make it simply and does'nt need to call all the record in my Post table :( 任何人都可以简单地做到这一点,不需要调用我的Post表中的所有记录:(

I think something like this might work: 我认为这样可能有效:

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.

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