0

模型

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变化,但每次都失败了。

谢谢您的帮助!

对于电话,我正在使用这些表单按钮,所以我选择了:

<% 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的帮助!

4

3 回答 3

2

您可以使用.order("RAND()")mysql 和.order("RANDOM()")postgre。

更新:没有重复。

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 次,每次都在 names 中添加一个 uniq 名称

# how to call
names = []
16.times do
  if record = Model.energe(1, 1, names)
    names << record
  end
end
于 2013-02-10T01:52:56.830 回答
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
于 2013-02-10T02:54:27.957 回答
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)
于 2013-02-10T03:01:27.093 回答