0

简单的问题,这段代码会确保 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]

就在数组的中间是一个重复。我仍在寻找代码以防止连续两次获得相同的记录。

4

1 回答 1

1

由于您正在加载所有想法,因此不清楚为什么要返回数据库以获取随机想法。

def random_thought
  @thoughts ||= Thought.all.shuffle
  @thoughts.pop
end

请注意,@thoughts 将所有想法存储到一个实例变量中,下次调用 random_thought 时该实例变量仍应存在于当前请求中,而 random_thoughts ||= 将不起作用,因为它将想法存储在局部变量中。这意味着每次你请求一个随机想法时它都会消失,这会导致每次都加载所有想法,这是你的日志输出所暗示的,从而增加了你得到重复的机会,而且效率非常低。如果所有想法都存储在@thoughts 中并被打乱,那么在弹出所有@thoughts 之前,您可以保证永远不会运行。

亚历克斯 D 是正确的:效率。为了您的实验目的,可以加载所有想法;如果这是一个生产站点,那将是一场灾难。有关一些想法,请查看 SQL Antipatterns 书,在此处的幻灯片共享中进行了总结:http ://www.slideshare.net/billkarwin/sql-antipatterns-strike-back

跳到幻灯片 148。您实际上想要查询最大 ID,根据随机数选择一个 ID,然后获取下一个最高的现有记录。

于 2013-06-08T04:08:31.273 回答