Skip to content

Commit

Permalink
Fix polymorphic association target classes not set correctly in subcl…
Browse files Browse the repository at this point in the history
…asses

Fixes #3631
  • Loading branch information
mshibuya committed Jun 17, 2023
1 parent 75a6927 commit 2a89ebc
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 2 deletions.
2 changes: 1 addition & 1 deletion lib/rails_admin/adapters/active_record/association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def field_type

def klass
if options[:polymorphic]
polymorphic_parents(:active_record, model.name.to_s, name) || []
polymorphic_parents(:active_record, association.active_record.name.to_s, name) || []
else
association.klass
end
Expand Down
2 changes: 1 addition & 1 deletion lib/rails_admin/adapters/mongoid/association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ def field_type

def klass
if polymorphic? && %i[referenced_in belongs_to].include?(macro)
polymorphic_parents(:mongoid, model.name, name) || []
polymorphic_parents(:mongoid, association.inverse_class_name, name) || []
else
association.klass
end
Expand Down
12 changes: 12 additions & 0 deletions spec/rails_admin/adapters/active_record/association_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,18 @@ class FieldTestWithSymbolForeignKey < FieldTest
expect(@category.associations.detect { |a| a.name == :librarian }.klass).to eq [ARUser]
expect(@blog.associations.detect { |a| a.name == :librarian }.klass).to eq [ARProfile]
end

describe 'on a subclass' do
before do
class ARReview < ARComment; end
allow(RailsAdmin::Config).to receive(:models_pool).and_return(%w[ARBlog ARPost ARCategory ARUser ARProfile ARComment ARReview])
end
subject { RailsAdmin::AbstractModel.new(ARReview).associations.detect { |a| a.name == :commentable } }

it 'returns correct target klasses' do
expect(subject.klass).to eq [ARBlog, ARPost]
end
end
end

describe 'polymorphic inverse has_many association' do
Expand Down
12 changes: 12 additions & 0 deletions spec/rails_admin/adapters/mongoid/association_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,18 @@ class MongoNote
expect(subject.read_only?).to be_falsey
expect(subject.nested_options).to be_nil
end

describe 'on a subclass' do
before do
class MongoReview < MongoComment; end
allow(RailsAdmin::Config).to receive(:models_pool).and_return(%w[MongoBlog MongoPost MongoCategory MongoUser MongoProfile MongoComment MongoReview])
end
subject { RailsAdmin::AbstractModel.new(MongoReview).associations.detect { |a| a.name == :commentable } }

it 'returns correct target klasses' do
expect(subject.klass).to eq [MongoBlog, MongoPost]
end
end
end

describe 'polymorphic inverse has_many association' do
Expand Down

0 comments on commit 2a89ebc

Please sign in to comment.