From 0a7a52405e03dfe2517eea5adf042426bb3d774a Mon Sep 17 00:00:00 2001 From: Ryan MacGillivray Date: Fri, 5 Aug 2022 16:29:35 +0100 Subject: [PATCH] Update docs for `.unscoped` to be explicit about associations We recently ran into an issue where we used `.unscoped` as part of a method chain without realising that it would also unset the scoping of the association. It feels like this would be useful information to surface in the documentation so that there's a clear source of truth on how the method behaves. --- activerecord/lib/active_record/scoping/default.rb | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/activerecord/lib/active_record/scoping/default.rb b/activerecord/lib/active_record/scoping/default.rb index e776b19502..465c4efbcd 100644 --- a/activerecord/lib/active_record/scoping/default.rb +++ b/activerecord/lib/active_record/scoping/default.rb @@ -24,14 +24,22 @@ module ActiveRecord # Returns a scope for the model without the previously set scopes. # # class Post < ActiveRecord::Base + # belongs_to :user + # # def self.default_scope # where(published: true) # end # end # + # class User < ActiveRecord::Base + # has_many :posts + # end + # # Post.all # Fires "SELECT * FROM posts WHERE published = true" # Post.unscoped.all # Fires "SELECT * FROM posts" # Post.where(published: false).unscoped.all # Fires "SELECT * FROM posts" + # User.find(1).posts # Fires "SELECT * FROM posts WHERE published = true AND posts.user_id = 1" + # User.find(1).posts.unscoped # Fires "SELECT * FROM posts" # # This method also accepts a block. All queries inside the block will # not use the previously set scopes.