Tuesday, 6 August 2013

Making PublicActivity gem notifications SQL query more efficient

Making PublicActivity gem notifications SQL query more efficient

Im using the public activity gem as seen in railscasts video
http://railscasts.com/episodes/406-public-activity. The query below
fetches all of the notifications for the current_user.
application_controller.rb
def notifications
PublicActivity::Activity.where(recipient_id:
current_user.id).order("created_at DESC")
end
Activities are a polymorphic model which belongs to comments, questions
and answers through the trackable_id and trackable_type columns. (Note,
I'm including the migration as the gem doesn't generate an activity model
in the app.)
class CreateActivities < ActiveRecord::Migration
def self.up
create_table :activities do |t|
t.belongs_to :trackable, :polymorphic => true
t.belongs_to :owner, :polymorphic => true
t.string :key
t.text :parameters
t.belongs_to :recipient, :polymorphic => true
t.timestamps
end
This query gets the job done however the stack trace below shows thats its
not the most efficient way of retrieving the activities.
How could I refactor the notifications method to reduce the amount of
individual queries performed?
PublicActivity::Activity Load (0.4ms) SELECT `activities`.* FROM
`activities` WHERE `activities`.`recipient_id` = 1 ORDER BY created_at
DESC LIMIT 8
Answer Load (0.2ms) SELECT `answers`.* FROM `answers` WHERE
`answers`.`id` = 18 LIMIT 1
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2
LIMIT 1
Question Load (0.2ms) SELECT `questions`.* FROM `questions` WHERE
`questions`.`id` = 21 LIMIT 1
Rendered public_activity/answer/_create.html.erb (4.3ms)
Answer Load (0.2ms) SELECT `answers`.* FROM `answers` WHERE
`answers`.`id` = 10 LIMIT 1
CACHE (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
Question Load (0.3ms) SELECT `questions`.* FROM `questions` WHERE
`questions`.`id` = 16 LIMIT 1
Rendered public_activity/answer/_correct.html.erb (3.5ms)
Comment Load (0.2ms) SELECT `comments`.* FROM `comments` WHERE
`comments`.`id` = 7 LIMIT 1
CACHE (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
Question Load (0.2ms) SELECT `questions`.* FROM `questions` WHERE
`questions`.`id` = 14 LIMIT 1
Rendered public_activity/comment/_create.html.erb (3.7ms)
Answer Load (0.2ms) SELECT `answers`.* FROM `answers` WHERE
`answers`.`id` = 6 LIMIT 1
CACHE (0.0ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 2 LIMIT 1
CACHE (0.0ms) SELECT `questions`.* FROM `questions` WHERE
`questions`.`id` = 14 LIMIT 1
if anyone needs more code just shout.

No comments:

Post a Comment