Created
June 23, 2023 15:23
-
-
Save rzane/df63c092cc7a5d94a6ab00f8dfb9fddc to your computer and use it in GitHub Desktop.
ActiveRecord polymorphic associations don't accept a custom primary key?
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'bundler/inline' | |
require 'minitest/autorun' | |
gemfile true do | |
source 'https://rubygems.org' | |
gem 'activerecord', require: 'active_record' | |
gem 'sqlite3' | |
end | |
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:') | |
ActiveRecord::Schema.define do | |
create_table :users, force: true do |t| | |
t.integer :other_id | |
end | |
create_table :attachments, force: true do |t| | |
t.string :record_type | |
t.integer :record_id | |
end | |
end | |
class User < ActiveRecord::Base | |
has_one :attachment, as: :record, inverse_of: :record, primary_key: :other_id | |
end | |
class Attachment < ActiveRecord::Base | |
belongs_to :record, polymorphic: true, touch: true | |
end | |
class PolymorphicHasOneTest < Minitest::Spec | |
it 'uses the custom primary key' do | |
user = User.create!(other_id: 42) | |
attachment = user.create_attachment! | |
# This assertion fails because `attachment.record_id` is actually `user.id` | |
assert_equal 42, attachment.record_id | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment