gpt4 book ai didi

ruby-on-rails - 使用 will_paginate 对博客文章的随机列表进行分页

转载 作者:行者123 更新时间:2023-12-03 16:02:31 27 4
gpt4 key购买 nike

我想让用户能够以随机顺序翻阅我的博客文章。

我不能像这样实现它:

@posts = Post.paginate :page => params[:page], :order => 'RANDOM()'

:order每次查询都会调用参数,因此我冒着重复博客文章的风险。

做到这一点的最佳方法是什么?

最佳答案

RAND 在 MySQL 中接受一个种子:

RAND(N) 

来自 MySQL docs :

RAND(), RAND(N)

Returns a random floating-point value v in the range 0 <= v < 1.0. If a constant integer argument N is specified, it is used as the seed value, which produces a repeatable sequence of column values. In the following example, note that the sequences of values produced by RAND(3) is the same both places where it occurs.



其他数据库应该有类似的功能。

如果您使用 每次调用 RAND 时的种子,请求之间的顺序将保持一致,您可以相应地进行分页。

然后,您可以将种子存储在用户的 session 中 - 这样每个用户都会看到一组他们独有的结果。

关于ruby-on-rails - 使用 will_paginate 对博客文章的随机列表进行分页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/810267/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com