使用Rails 3,我是一個RoR noob,所以這可能很簡單,但我似乎無法弄清楚。我的意思是,我可以讓它工作,但我無法弄清楚最好的方法。Ruby on Rails隨機發布通過acts_as_taggable_on_steroids
好吧,我已經閱讀了關於通過Rails選擇隨機記錄的所有問題,我認爲答案非常簡單,大部分。然而,我不得不在選擇一個隨機記錄之前調用acts_as_taggable_on_steroids方法,所以我的首選技術不起作用,因爲find_tagged_with返回一個數組。
這是一個由兩部分組成的問題。從性能的角度來看,我需要知道哪些方法是最好的,以及如果使用不同的tag.name多次調用此方法,如何防止重複帖子出現在結果中。
下面是到目前爲止,我已經試過的方法:
def related_posts(tag)
rand_id = rand(Post.find_tagged_with(tag.name).count)
rand_record = Post.find_tagged_with(tag.name, :conditions => [ "posts.id >= ?", rand_id], :limit => 2)
end
def related_posts(tag)
rand_id = rand(Post.find_tagged_with(tag.name).count)
post = Post.find_tagged_with(tag.name, :offset => rand_id, :limit => 2)
end
def related_posts(tag)
post = Post.find_tagged_with(tag.name, :order => 'RAND()', :limit => 2)
end
def related_posts(tag)
posts = Post.find_tagged_with(tag.name)
offset = rand(posts.count)
posts.find(:offset =>offset) #doesn't work since this is an array at this point :(
end
def related_posts(tag)
related = []
posts = Post.find_tagged_with(tag.name)
related << random_post(posts)
related << random_post(posts)
return related
end
def random_post(obj)
rand_id = rand(obj.count)
rand_record = obj[rand_id]
end
編輯:這似乎是最快的,雖然我很少遇到性能測試Rails應用。
def related_posts(tag)
posts = Post.find_tagged_with(tag.name).sort_by { rand }.slice(0, 2)
end
無論誰發生回答這個問題,你能否也請解釋究竟發生了什麼?它是隨機化記錄並在數據庫級別或其他方面進行排序。此外,這通常意味着與軌道應用程序的性能明智嗎?
slice(0,2)和.first(2)之間是否存在性能差異?仍然很難讓性能測試工作。我會保存一個新的問題。 –
好問題。我必須運行一些基準才能看到! –