如何从Ruby中的表中返回唯一的随机行?

时间:2013-02-10 00:11:32

标签: ruby random

模型

class Answer < ActiveRecord::Base
def self.energy(v, w)
  a = self.where('energy_id = ? AND weight = ?', v, w)
  a.offset(rand(a.count)).first.name
end

视图

<%= form_for(@answer) do |f| %>
  <%= f.submit "#{Answer.energy(3, 1)}", name: "answer", class: "btn" %>
  <%= f.submit "#{Answer.energy(4, 1)}", name: "answer", class: "btn" %>
<% end %>

我有,并且它正确地返回一个随机值。我打电话给这36次(18对2),我不希望同样的值返回不止一次。我尝试了各种.pop版本,但每次都失败了。

感谢您的帮助!

FOR CALL,我正在使用这些表单按钮,所以我选择了:

<% names = [] %>

<div id='one' class='center'>
  <%= form_for(@answer) do |f| %>
    <%= f.submit "#{record = Answer.energy(3, 1, names)}", name: "answer", class: "btn btn-large btn-primary" %>
    <% names << record %>
    <%= f.submit "#{record = Answer.energy(4, 1, names)}", name: "answer", class: "btn btn-large btn-primary" %>
    <% names << record %>
  <% end %>
</div>
~~ 17 more times ~~

就像一个魅力!谢谢,jvnill,求助!

3 个答案:

答案 0 :(得分:2)

你可以为mysql使用.order("RAND()"),为postgre使用.order("RANDOM()")

更新:没有重复。

def self.energy(v, w)
  where('energy_id = ? AND weight = ?', v, w).limit(16).uniq.pluck(:name)
end

更新:16次,无重复

这将返回与能量和重量匹配的第一个随机记录,但不包括在except_names

# model
def self.energy(v, w, except_names = [])
  klass = where('energy_id = ? AND weight = ?', v, w)
  klass = klass.where('name NOT IN (?)', except_names) if except_names.any?
  klass.order('RAND()').first.name
end

这会将方法调用16次,每次都将uniq名称添加到名称

# how to call
names = []
16.times do
  if record = Model.energe(1, 1, names)
    names << record
  end
end

答案 1 :(得分:1)

def self.energy(v, w)
  c = []
  a = self.where('energy_id = ? AND weight = ?', v, w)
  b = a.offset(rand(a.count)).first.name
  unless c.include?(b) do
    puts b
    c << b
    end
end

答案 2 :(得分:1)

如果你正在调用它16次,你可以传递已经可用的行作为参数吗?如果是,那么这会有效吗?

def self.energy(v, w, records = [])
  a = self.where("energy_id = ? AND weight = ? AND id NOT IN ('-1',?)", v, w, Array(records).map(&:to_param))
  a.offset(rand(a.count)).first.name
end

用法:

records = []
16.times do
 records << Answer.energy(10, 5, records)
end

您也可以传递单个记录而不是数组:

other_record = Answer.energy(10,5)
Answer.energy(10, 5, other_record)