我已經在鐵軌下面的代碼從列表中拾取隨機項目,而不重複
@related = []
while @related.compact.size < 3
@tag = @car.tag_list.sample #pick a tag from the @car's tag_list
@sametags = Car.tagged_with(@tag) # get all cars with that tag
@related.push((@sametags - Array(@car) - @related.compact).sample) #put that car in @related
@counter = @counter + 1 #increment
break if @counter == 10 #stop if its taking too long
end
我深知這個代碼是非常低效的,但我的紅寶石扒不爲它尚未...
基本上我需要做的就是用3個帶有相似標籤的汽車模型隨機填充@related
,這樣他們就不會重複。
但這也可能選擇@car本身 – 2013-03-15 13:57:13
試試我更新的答案。它基本上不包括'@ car'。並且也使用汽車的所有標籤列表:) – jvnill 2013-03-15 13:59:56
'order('rand()')'不是交叉DB,IIRC。 – 2013-03-15 14:02:33