Rails 分页时随机 ActiveRecord
我试图在对它们进行分页时以随机顺序显示一系列照片。问题是,在分页的每一页上都会重新生成随机数组;这样用户就可以在第 2 页上看到他已经在第 1 页上看到过的照片。蹩脚。这是我的控制器:
def index
@photos = Photo.order('random()').paginate(:per_page => 12, :page => params[:page])
end
我思考了一段时间,想不出任何合理的解决方案。这很容易做到吗?这似乎是一个非常常见的功能,但我可能不得不放弃随机的东西。想法?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过指定种子向随机性引入一些有序性。使用此功能,后续调用将为您提供可重复的排序。
每个数据库都提供不同的方式来指定种子值。例如,在 MySQL 中,
这里 0.5 将是 rand() 函数的种子。
同样,Postgres 有一个
setseed()
函数。我不确定你正在使用什么数据库。无论如何,我希望你能明白。You can introduce some orderness to randomness by specifying a seed. Using this, the subsequent calls would give you repeatable ordering.
Each database offers a different way to specify the seed value. For e.g., in MySQL,
Here 0.5 would be the seed to
rand()
function.Similarly, Postgres has a
setseed()
function. I am not sure what database you are using. Anyway, I hope you get the idea.