Skip to content

Instantly share code, notes, and snippets.

@rzane
Created June 23, 2023 15:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rzane/df63c092cc7a5d94a6ab00f8dfb9fddc to your computer and use it in GitHub Desktop.
Save rzane/df63c092cc7a5d94a6ab00f8dfb9fddc to your computer and use it in GitHub Desktop.
ActiveRecord polymorphic associations don't accept a custom primary key?
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