2016-04-19 8 views
0

私はRails 5 JSON APIを書いています。評価の高い上位N件の投稿をキャッシュする方法は?

私は平均評価に基づいてトップNブログ記事を返すアクションを持っています。応答時間を短くするために、私はpostsaverage_ratingの列を持つようにデータベースを非正規化しました。

# posts_controller.rb 
def top 
    quantity = params[:quantity] 

    if quantity.to_i > 0 
    render json: { 
     posts: cached_top_posts(quantity) 
    }, status: :ok 
    else 
    render json: '', status: :unprocessable_entity 
    end 
end 

def cached_top_posts(quantity) 
    Rails.cache.fetch(['top', quantity], expires_in: 1.hour) do 
    Post.limit(quantity).as_json(only: [:title, :content, :average_rating]) 
    end 
end 

私はこれが最適にはほど遠いことを認識しています(average_rating順がモデルそのものである):

は、私はまた、キャッシュそうのようなすべてのクエリです。

それが大幅時にすでにキャッシュされた上位1000投稿、それはキャッシュ100回の投稿ませんが、ポストの同じ量を要求する場合ならば、それははるかに良いだろう、応答時間を改善し、代わりに最初のになるだろうけれどものうち10030の投稿がキャッシュされました。1000です。

これを達成するにはどうすればよいでしょうか?

答えて

0

私は良い夜の睡眠を取った後、単純な結論がちょうど私の心に入った。

ここでは、次のとおりです。

# posts_controller.rb 
def cached_top_posts(quantity) 
    data = Rails.cache.read('top_posts') 
    if data.nil? || data[:quantity] < quantity 
    data = { 
     :quantity => quantity, 
     :posts => Post.limit(quantity).as_json(only: [:title, :content, :average_rating]) 
    } 
    Rails.cache.write('top_posts', data, expires_in: 1.hour) 
    end 
    data[:posts][0...quantity] 
end 
関連する問題