Skip to content

Commit aacbb5c

Browse files
committed
Merge pull request rails#53176 from Stellenticket/polymorphic_inverse_of_chain
allow to autosave associations with polymorphic has many through join…
2 parents 3d62fc0 + 36685b1 commit aacbb5c

File tree

4 files changed

+24
-1
lines changed

4 files changed

+24
-1
lines changed

activerecord/CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,7 @@
1+
* Allow to save records with polymorphic join tables that have inverse of specified.
2+
3+
*Markus Doits*
4+
15
* Fix association scopes applying on the incorrect join when using a polymorphic `has_many through:`.
26

37
*Joshua Young*

activerecord/lib/active_record/associations/has_many_through_association.rb

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,13 @@ def build_record(attributes)
9393
@through_scope = scope
9494
record = super
9595

96-
inverse = source_reflection.inverse_of
96+
inverse =
97+
if source_reflection.polymorphic?
98+
source_reflection.polymorphic_inverse_of(record.class)
99+
else
100+
source_reflection.inverse_of
101+
end
102+
97103
if inverse
98104
if inverse.collection?
99105
record.send(inverse.name) << build_through_record(record)

activerecord/test/cases/associations/has_many_through_associations_test.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,9 @@
3838
require "models/session"
3939
require "models/sharded"
4040
require "models/cpk"
41+
require "models/zine"
42+
require "models/interest"
43+
require "models/human"
4144

4245
class HasManyThroughAssociationsTest < ActiveRecord::TestCase
4346
fixtures :posts, :readers, :people, :comments, :authors, :categories, :taggings, :tags,
@@ -1320,6 +1323,15 @@ def test_has_many_through_with_polymorphic_source
13201323
assert_equal [tags(:general)], post.reload.tags
13211324
end
13221325

1326+
def test_has_many_through_with_polymorhic_join_model
1327+
zine = Zine.create!
1328+
1329+
assert_nothing_raised { zine.polymorphic_humans.build.save! }
1330+
1331+
assert_equal 1, zine.polymorphic_humans.count
1332+
assert_equal 1, zine.interests.count
1333+
end
1334+
13231335
def test_has_many_through_obeys_order_on_through_association
13241336
owner = owners(:blackbeard)
13251337
assert_includes owner.toys.to_sql, "pets.name desc"

activerecord/test/models/zine.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,4 +2,5 @@
22

33
class Zine < ActiveRecord::Base
44
has_many :interests, inverse_of: :zine
5+
has_many :polymorphic_humans, through: :interests, source_type: "Human"
56
end

0 commit comments

Comments
 (0)