Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Eager-load the user feed to avoid repetitive queries #17

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions app/models/user.rb
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@ def feed
WHERE follower_id = :user_id"
Micropost.where("user_id IN (#{following_ids})
OR user_id = :user_id", user_id: id)
.includes(:user, image_attachment: :blob)
end

# Follows a user.
Expand Down
39 changes: 35 additions & 4 deletions test/integration/microposts_interface_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,35 @@

class MicropostsInterfaceTest < ActionDispatch::IntegrationTest

class QueryCountHandler
attr_reader :count

def initialize
@count = 0
end

def call(name, started, finished, unique_id, payload)
# puts payload[:sql]
@count += 1
end
end

def setup
@user = users(:michael)
end

def count_sql(message)
warn "Counting SQL queries for: #{message}"

count_handler = QueryCountHandler.new
ActiveSupport::Notifications.subscribe 'sql.active_record', count_handler

yield

warn "Observed #{count_handler.count} SQL queries"
ActiveSupport::Notifications.unsubscribe count_handler
end

test "micropost interface" do
log_in_as(@user)
get root_path
Expand All @@ -18,12 +43,18 @@ def setup
# Valid submission
content = "This micropost really ties the room together"
image = fixture_file_upload('kitten.jpg', 'image/jpeg')

assert_difference 'Micropost.count', 1 do
post microposts_path, params: { micropost: { content: content,
image: image } }
count_sql 'Create a valid post' do
post microposts_path, params: { micropost: { content: content,
image: image } }
end
assert assigns(:micropost).image.attached?
end

count_sql 'Follow redirect after posting' do
follow_redirect!
end
assert assigns(:micropost).image.attached?
follow_redirect!
assert_match content, response.body
# Delete a post.
assert_select 'a', 'delete'
Expand Down