Skip to content

Commit f7e19de

Browse files
authored
Merge pull request rails#41892 from kamipo/fix_default_scope_table_alias
Fix user-defined `self.default_scope` to respect table alias
2 parents 3b1fae4 + b576dd0 commit f7e19de

File tree

2 files changed

+5
-6
lines changed

2 files changed

+5
-6
lines changed

activerecord/lib/active_record/scoping/default.rb

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -146,9 +146,7 @@ def build_default_scope(relation = relation(), all_queries: nil)
146146
if default_scope_override
147147
# The user has defined their own default scope method, so call that
148148
evaluate_default_scope do
149-
if scope = default_scope
150-
relation.merge!(scope)
151-
end
149+
relation.scoping { default_scope }
152150
end
153151
elsif default_scopes.any?
154152
evaluate_default_scope do

activerecord/test/cases/adapters/postgresql/schema_test.rb

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,7 @@ class Song < ActiveRecord::Base
7676
class Album < ActiveRecord::Base
7777
self.table_name = "music.albums"
7878
has_and_belongs_to_many :songs
79+
def self.default_scope; where(deleted: false); end
7980
end
8081

8182
def setup
@@ -149,14 +150,14 @@ def test_habtm_table_name_with_schema
149150
ActiveRecord::Base.connection.drop_schema "music", if_exists: true
150151
ActiveRecord::Base.connection.create_schema "music"
151152
ActiveRecord::Base.connection.execute <<~SQL
152-
CREATE TABLE music.albums (id serial primary key);
153+
CREATE TABLE music.albums (id serial primary key, deleted boolean default false);
153154
CREATE TABLE music.songs (id serial primary key);
154155
CREATE TABLE music.albums_songs (album_id integer, song_id integer);
155156
SQL
156157

157158
song = Song.create
158-
Album.create
159-
assert_equal song, Song.includes(:albums).references(:albums).first
159+
album = song.albums.create
160+
assert_equal song, Song.includes(:albums).where("albums.id": album.id).first
160161
ensure
161162
ActiveRecord::Base.connection.drop_schema "music", if_exists: true
162163
end

0 commit comments

Comments
 (0)