我在 Rails 中有以下代码
@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
我很清楚这段代码效率很低,但我的红宝石印章还没有准备好......
基本上我需要做的是@related
随机填充 3 个具有相似标签的汽车模型,它们不会重复。