轨道上的下一个对象问题 [英] next object problem on rails

查看:45
本文介绍了轨道上的下一个对象问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

视频表

id
title
votes_count

视频控制器

def show
 @video = Video.find(params[:id])
 @next_video = Video.order("votes_count DESC").where("votes_count < ?", @video.votes_count).first
 @previous_video = Video.order("votes_count ASC").where("votes_count > ?", @video.votes_count).first
end

问题是有些视频的票数相同.当我改变 votes_count<to votes_count<= 它开始在 2 个视频之间循环.有任何想法吗?谢谢.

The problem is that there are videos that have the same votes_count number. When i change votes_count< to votes_count<= it starts to loop between 2 videos. Any ideas? Thanks.

推荐答案

解决这个问题的主要关键是你需要明确地包含一个二级排序字段,这将使你确定解决带有相同的 votes_count.您还需要将 >= 拆分为两个单独的子句,因为您只想在主要字段为 = 时评估次要字段.

The main key to solving this problem is that you need to explicitly include a secondary sort field, that will give you the certainty to resolve the issue of rows with the same votes_count. You also need to split up the >= into two separate clauses because you only want to evaluate the secondary field when the primary is =.

现在,为了获得加分,我还将您的代码重构为模型上的方法,这样您的控制器就变成了……

Now, for bonus points, I'm also going to refactor your code as methods on your model, so your controller becomes just...

def show
  @video = Video.find params[:id]
end

然后你的模型变成...

And your model becomes...

def next
  self.class.
    order( "votes_count, id" ).
    where( "votes_count > :votes_count OR ( votes_count = :votes_count AND id > :id )", attributes.symbolize_keys ).first
end

def previous
  self.class.
    order( "votes_count DESC, id DESC" ).
    where( "votes_count < :votes_count OR ( votes_count = :votes_count AND id < :id )", attributes.symbolize_keys ).first
end

现在在您看来,您可以只引用 @video.next@video.previous

And now in your view you can just refer to @video.next and @video.previous

这篇关于轨道上的下一个对象问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆