Rails 3を使用していて、私はRoR初心者なので、これは簡単かもしれませんが、理解できないようです。つまり、動作させることはできますが、最善の方法を見つけることができません。
わかりました。Railsを介したランダムレコードの選択に関するSOに関するすべての質問を読みましたが、ほとんどの場合、答えは非常に簡単だと思います。ただし、ランダムなレコードを選択する前に、acts_as_taggable_on_steroidsメソッドを呼び出す必要があります。そのため、find_tagged_withが配列を返すため、私の好みの手法は機能しません。
これは2部構成の質問です。パフォーマンスの観点から、これらのメソッドのどれが最適であるか、また、このメソッドが異なる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
この質問にたまたま答えた人は誰でも、正確に何が起こっているのか説明していただけますか?レコードをランダム化し、データベースレベルで並べ替えるのですか。また、それは通常、Railsアプリのパフォーマンスに関して何を意味しますか?