model
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
view
<%= 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 %>
I have that, and it returns a random value, properly. I’m calling this 36 times though (18 pairs of 2), and I don’t want the same value returned more than once, ever. I tried all kinds of .pop variations, but failed every time.
Thanks for the help!
FOR THE CALL, I’m using these form buttons, so I went with:
<% 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 ~~
works like a charm! Thanks, jvnill, for the help!
you can user
.order("RAND()")for mysql and.order("RANDOM()")for postgre.UPDATE: no duplicates.
UPDATE: 16 times, no duplicate
this returns the first random record that matches the energy and weight and is not included in except_names
this calls the method 16 times, each time adding a uniq name to names