jeudi 26 juin 2014

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


Vote count:

0




I am having performance issues on one of my api views so I ran the Bullet gem and found some major N+1 issues with the view.


The api is being consumed so the format has to remain identical.


Bullet N+1 output:



localhost:3000/api/v1/games/1/game_feed N+1 Query detected

CompletedQuest => [:comments] Add to your 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 I don't know how to accomplish the fix. Here are the relevant parts.


View:



json.game_feed(@game_photos) do |f|
json.extract! f, :id, :user_id, :username, :image_url_original, :comments_count, :likes_count
json.comments f.comments do |comment|
json.(comment, :username, :comment)
end
json.likes f.likes do |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 basically for each photo in the feed, it then grabs every comment & likes for ever record - obviously this is bad and I see why, but I can't figure out how to fix it with my current structure.


Any help would be appreciated - but one thing is the structure of the JSON must remain identical.



asked 1 min ago






Aucun commentaire:

Enregistrer un commentaire