Skip to content

Instantly share code, notes, and snippets.

@lfittl
Last active August 29, 2015 14:04
Show Gist options
  • Select an option

  • Save lfittl/f0763350d57c4bd8d0c3 to your computer and use it in GitHub Desktop.

Select an option

Save lfittl/f0763350d57c4bd8d0c3 to your computer and use it in GitHub Desktop.
Rails default_scope = evil
class Notification
belongs_to :user
default_scope { order('id desc') }
end
class User
has_many :notifications
end
# notifications.html.erb
current_user.notifications.each do |n|
# Elsewhere
current_user.notifications.update_all(seen: true)
# => Leads to
UPDATE "notifications" SET "seen" = 't' WHERE "notifications"."id" IN (SELECT "notifications"."id" FROM "notifications" WHERE "notifications"."user_id" = 8 ORDER BY id desc);
QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------------------------------
Update on notifications (cost=8.33..16.37 rows=1 width=1618)
-> Nested Loop (cost=8.33..16.37 rows=1 width=1618)
-> HashAggregate (cost=8.19..8.20 rows=1 width=32)
-> Subquery Scan on "ANY_subquery" (cost=8.17..8.18 rows=1 width=32)
-> Sort (cost=8.17..8.17 rows=1 width=4)
Sort Key: notifications_1.id
-> Index Scan using index_notifications_on_user_id on notifications notifications_1 (cost=0.14..8.16 rows=1 width=4)
Index Cond: (user_id = 8)
-> Index Scan using notifications_pkey on notifications (cost=0.14..8.16 rows=1 width=1590)
Index Cond: (id = "ANY_subquery".id)
class Notification
belongs_to :user
scope :sorted, -> { order('id desc') }
end
class User
has_many :notifications
end
# notifications.html.erb
current_user.notifications.sorted.each do |n|
# Elsewhere
current_user.notifications.update_all(seen: true)
# => Leads to
UPDATE "notifications" SET "seen" = 't' WHERE "notifications"."user_id" = 8
QUERY PLAN
-------------------------------------------------------------------------------------------------------------
Update on notifications (cost=0.14..8.16 rows=1 width=1590)
-> Index Scan using index_notifications_on_user_id on notifications (cost=0.14..8.16 rows=1 width=1590)
Index Cond: (user_id = 8)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment