简单的问题,这段代码会确保 rand() 调用不会连续两次返回相同的记录吗?
从点击测试来看,似乎是这样,但我真的没有信心。
def thoughts
last_thought = 0 if last_thought == nil #this is the part that seems wrong for my goal
th = Array.new
Thought.all.each do |t|
th << t.id
end
th.pop(last_thought)
@rand_thought = Thought.find(rand(th.first..th.last))
last_thought = @rand_thought.id
end
根据@user198201 的建议,我将代码修改为:
def thoughts
shuffle_thought ||= Thought.all.shuffle
@rand_thought = shuffle_thought.pop
@rand_thought
end
然后为了测试,我添加了这个方法:
def thinker
a = Array.new
20.times do
a << thoughts.id
end
a
end
这是我现在在 Rails 控制台中得到的:
t = ThoughtController.new
=> #<'思想控制器:0x007f95636ae000>
t.thought.id
Thought Load (0.4ms) SELECT "thoughts".* FROM "thoughts"
=> 7
思想家
Thought Load (0.4ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.4ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.3ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
Thought Load (0.2ms) SELECT "thoughts".* FROM "thoughts"
=> [5, 9, 4, 7, 4, 5, 8, 7, 7, 1, 6, 1, 8, 6, 4, 1, 2, 7, 3, 2]
就在数组的中间是一个重复。我仍在寻找代码以防止连续两次获得相同的记录。