sql - Nested json jbuilder for photo feed having n+1 major issues -


i having performance issues on 1 of api views ran bullet gem , found major n+1 issues view.

the api being consumed format has remain identical.

bullet n+1 output:

localhost:3000/api/v1/games/1/game_feed n+1 query detected
completedquest => [:comments] add finder: :include => [:comments] n+1 query method call stack
/app/views/api/v1/games/game_feed.json.jbuilder:3:in block in _b3b681b668d1c2a5691a5b3f7c15bb8e' /app/views/api/v1/games/game_feed.json.jbuilder:1:in _b3b681b668d1c2a5691a5b3f7c15bb8e'

but don't know how accomplish fix. here relevant parts.

view:

json.game_feed(@game_photos) |f|   json.extract! f, :id, :user_id, :username, :image_url_original, :comments_count, :likes_count   json.comments f.comments |comment|     json.(comment, :username, :comment)   end   json.likes f.likes |like|     json.(like, :id, :user_id, :username)   end end 

controller:

@game_photos = completedquest.game_photos(@game.id) 

model:

def self.game_photos(game_id)   where("completed_quests.game_id = ?", game_id).order("completed_quests.id desc").just_photos end  scope :just_photos, -> { where.not( image_file_name: nil ) } 

model relationships:

# completedquests: belongs_to :user has_many :comments, dependent: :destroy has_many :likes, dependent: :destroy  # comments: belongs_to :completed_quest, counter_cache: true belongs_to :user 

so each photo in feed, grabs every comment & likes ever record - bad , see why, can't figure out how fix current structure.

any appreciated - 1 thing structure of json must remain identical.

you include associated comments in query follows:

# app/models/completed_quest.rb def self.game_photos(game_id)   includes(:comments).where("completed_quests.game_id = ?", game_id).order("completed_quests.id desc").just_photos end 

this include associated comments in result, when f.comments in view, there won't database query comments of each f instance.


Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -