Skip to content

Commit 2801ea6

Browse files
committed
Fix has_many through association assginments with custom scope and custom joining association name
`where_values_hash` method signature accepts `table_name` which is not always the same as the association name. So passing `through_association.reflection.name.to_s` as `table_name` in `through_scope_attributes` wasn't accurate for every case. This commit fixes the issue by passing the `table_name` taken from `through_association.reflection.klass.table_name` instead.
1 parent 5cbf615 commit 2801ea6

File tree

3 files changed

+16
-1
lines changed

3 files changed

+16
-1
lines changed

activerecord/lib/active_record/associations/has_many_through_association.rb

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ def build_through_record(record)
7070

7171
def through_scope_attributes
7272
scope = through_scope || self.scope
73-
attributes = scope.where_values_hash(through_association.reflection.name.to_s)
73+
attributes = scope.where_values_hash(through_association.reflection.klass.table_name)
7474
except_keys = [
7575
*Array(through_association.reflection.foreign_key),
7676
through_association.reflection.klass.inheritance_column

activerecord/test/cases/associations/has_many_through_associations_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1359,6 +1359,18 @@ def test_insert_records_via_has_many_through_association_with_scope
13591359
assert_equal [member], club.favorites
13601360
end
13611361

1362+
def test_insert_records_via_has_many_through_association_with_scope_and_association_name_different_from_the_joining_table_name
1363+
club = Club.create!
1364+
member = Member.create!
1365+
Membership.create!(club: club, member: member)
1366+
1367+
club.custom_favorites << member
1368+
assert_equal [member], club.custom_favorites
1369+
1370+
club.reload
1371+
assert_equal [member], club.custom_favorites
1372+
end
1373+
13621374
def test_has_many_through_unscope_default_scope
13631375
post = Post.create!(title: "Beaches", body: "I like beaches!")
13641376
Reader.create! person: people(:david), post: post

activerecord/test/models/club.rb

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,9 @@ class Club < ActiveRecord::Base
1010

1111
has_many :favorites, -> { where(memberships: { favorite: true }) }, through: :memberships, source: :member
1212

13+
has_many :custom_memberships, class_name: "Membership"
14+
has_many :custom_favorites, -> { where(memberships: { favorite: true }) }, through: :custom_memberships, source: :member
15+
1316
scope :general, -> { left_joins(:category).where(categories: { name: "General" }).unscope(:limit) }
1417

1518
accepts_nested_attributes_for :membership

0 commit comments

Comments
 (0)