Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Postgres从row中选择3个随机模型实例?_Ruby On Rails_Postgresql - Fatal编程技术网

Ruby on rails Postgres从row中选择3个随机模型实例?

Ruby on rails Postgres从row中选择3个随机模型实例?,ruby-on-rails,postgresql,Ruby On Rails,Postgresql,在我的Rails应用程序中,我想选择一个模型的三个随机实例,并在页面上呈现它们Model.order('RANDOM()').limit(3)起作用,但很明显,一旦DB表中有大量数据,它将严重影响加载时间,因此我正在寻找一些不仅在开发中有效的东西 下面是我的Rails视图中的行: <% featured = Product.order('RANDOM()').limit(3).where.not(photo_file_name: nil, sold_value: true) %>

在我的Rails应用程序中,我想选择一个模型的三个随机实例,并在页面上呈现它们
Model.order('RANDOM()').limit(3)
起作用,但很明显,一旦DB表中有大量数据,它将严重影响加载时间,因此我正在寻找一些不仅在开发中有效的东西

下面是我的Rails视图中的行:

<% featured = Product.order('RANDOM()').limit(3).where.not(photo_file_name: nil, sold_value: true) %>

有很多方法可以做到这一点。哪种方式最好取决于您的设置、产品数量等

ids = Product.pluck(:id).shuffle.slice(0,3)
featured = Product.where(id: ids)
只有两个查询,但如果您有一百万个产品,那么在Ruby中返回和洗牌就太多了。还有一个小竞争条件,即在您进行第二次呼叫之前,可以删除其中一个选定的ID

total = Product.count
featured = 3.times.map { Product.offset(rand(total).first }
四个查询,但最后三个是有效的。我的语法可能已关闭,并且其中可能存在一个逐个关闭的错误,因此请仔细检查
rand(total)
返回零或
total
时发生的情况。另外,对于某些数据库,
Product.count
的效率可能非常低