分页时随机Rails ActiveRecord [英] Rails random ActiveRecord while paginating

查看:66
本文介绍了分页时随机Rails ActiveRecord的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在分页时以随机顺序显示一系列照片.问题是,在分页的每一页上都会重新生成随机数组;因此用户可以在第2页上看到他已经在第1页上看到的照片.这是我的控制器:

I am trying to display a series of photos in random order while paginating them. Trouble is, on each page of the pagination the random array is regenerated; so a user can see photos on page 2 that he's already seen on page 1. Lame. Here's my controller:

def index
  @photos = Photo.order('random()').paginate(:per_page => 12, :page => params[:page])
end

我已经思考了一段时间,无法想到任何合理的解决方案.这容易做到吗?这似乎是一个非常普通的功能,但我可能只需要抛弃随机的东西.有想法吗?

I've been thinking it for a while and can't think of any reasonable solution. Is this easily doable? It seems like a pretty common function, but I may just have to ditch the random thing. Thoughts?

推荐答案

您可以通过指定种子来为随机性引入一些有序性.使用此功能,后续调用将为您提供可重复的排序.

You can introduce some orderness to randomness by specifying a seed. Using this, the subsequent calls would give you repeatable ordering.

每个数据库提供了一种不同的方法来指定种子值.例如,在MySQL中,

Each database offers a different way to specify the seed value. For e.g., in MySQL,

@photos = Photo.order('rand(0.5)').paginate(:per_page => 12, :page => params[:page])

这里是rand()函数的种子.

类似地,Postgres具有setseed()功能.我不确定您使用的是哪个数据库.无论如何,我希望你能明白.

Similarly, Postgres has a setseed() function. I am not sure what database you are using. Anyway, I hope you get the idea.

这篇关于分页时随机Rails ActiveRecord的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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