Skip to content

Commit

Permalink
Support polymorphic_name
Browse files Browse the repository at this point in the history
`polymorphic_name` was introduced in 5.2.0 but wasn't properly ported to CPK.
  • Loading branch information
marshall-lee committed Sep 8, 2023
1 parent 358ef9b commit 55b6062
Show file tree
Hide file tree
Showing 5 changed files with 24 additions and 3 deletions.
4 changes: 2 additions & 2 deletions lib/composite_primary_keys/associations/association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ def creation_attributes
attributes[key1] = owner[key2]
end

if reflection.options[:as]
attributes[reflection.type] = owner.class.base_class.name
if reflection.type
attributes[reflection.type] = owner.class.polymorphic_name
end
end

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,4 @@ def next_chain_scope(scope, reflection, next_reflection)
end
end
end
end
end
6 changes: 6 additions & 0 deletions test/fixtures/comments.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,3 +15,9 @@ user_comment_2:
article: second
person_id: 2
person_type: User

user_comment_3:
id: 4
article: first
person_id: 1
person_type: User1
9 changes: 9 additions & 0 deletions test/fixtures/user_with_polymorphic_name.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
class UserWithPolymorphicName < ActiveRecord::Base
self.table_name = "users"

has_many :comments, :as => :person

def self.polymorphic_name
"User1"
end
end
6 changes: 6 additions & 0 deletions test/test_polymorphic.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,10 @@ def test_clear_has_many_through
article.user_commentators = []
assert_equal(0, article.comments.size)
end

def test_polymorphic_has_many_with_polymorphic_name
comments = UserWithPolymorphicName.find(1).comments
assert_equal 1, comments[0].person_id
assert_equal "User1", comments[0].person_type
end
end

0 comments on commit 55b6062

Please sign in to comment.