ruby on rails - How to cache top N posts ordered by rating? -


i'm writing rails 5 json api.

i've got action returns top n blog posts based on average rating. in order achieve low response time, denormalized database such posts has average_rating column.

i'm caching every query so:

# 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)     post.limit(quantity).as_json(only: [:title, :content, :average_rating])   end end 

(order average_rating in model itself)

i aware far optimal.

whilst drastically improves response time when requesting same quantity of posts, better if, when cached top 1000 posts, not cache 100 posts, instead first 100 posts out of cached 1000.

what way achieve this?

well, after had night's sleep, simple conclusion came mind.

here is:

# 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 

Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -