Skip to content

Commit

Permalink
Fix ActiveRecord ObjectExtension has_one setter breaks with custom pr…
Browse files Browse the repository at this point in the history
…imary key class

Fixes #3460
  • Loading branch information
mshibuya committed Jan 29, 2022
1 parent 345dda6 commit 0e2e0e4
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/rails_admin/adapters/active_record/object_extension.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ def #{association.name}_id
end
def #{association.name}_id=(item_id)
self.#{association.name} = #{association.klass}.find_by_id(item_id)
self.#{association.name} = (#{association.klass}.find(item_id) rescue nil)
end
RUBY
end
Expand Down
1 change: 1 addition & 0 deletions spec/dummy_app/app/active_record/league.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ class League < ActiveRecord::Base
has_many :divisions, foreign_key: 'custom_league_id'
has_many :teams, -> { readonly }, through: :divisions
has_many :players, through: :teams
has_one :division, foreign_key: 'custom_league_id'

validates_presence_of(:name)

Expand Down
11 changes: 11 additions & 0 deletions spec/rails_admin/adapters/active_record/object_extension_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -56,5 +56,16 @@ class PlayerWithAutoSave < Player
expect(user.reload.team).to eq team
end
end

context 'when associated class has custom primary key' do
let(:league) { FactoryBot.build(:league).extend(RailsAdmin::Adapters::ActiveRecord::ObjectExtension) }
let(:division) { FactoryBot.create :division }

it 'does not break' do
league.division_id = division.id
league.save!
expect(league.reload.division).to eq division
end
end
end
end

0 comments on commit 0e2e0e4

Please sign in to comment.