Last active
June 2, 2021 01:50
-
-
Save HParker/8f8d69fb2a148d3f2994e0a72886ac95 to your computer and use it in GitHub Desktop.
Mixed typed polymorphic keys
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
# frozen_string_literal: true | |
require "bundler/inline" | |
gemfile(true) do | |
source "https://rubygems.org" | |
git_source(:github) { |repo| "https://github.com/#{repo}.git" } | |
gem "rails", github: "rails/rails", branch: "main" | |
gem "sqlite3" | |
end | |
require "active_record" | |
require "minitest/autorun" | |
require "logger" | |
# This connection will do for database-independent bug reports. | |
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:") | |
ActiveRecord::Base.logger = Logger.new(STDOUT) | |
ActiveRecord::Schema.define do | |
create_table :app_users, force: true do |t| | |
end | |
create_table :pm_users, force: true do |t| | |
t.string :uuid | |
end | |
create_table :api_users, force: true do |t| | |
t.integer :post_id | |
end | |
create_table :profiles, force: true do |t| | |
t.string :user_id | |
t.string :user_type | |
end | |
end | |
class AppUser < ActiveRecord::Base | |
alias_attribute :primary_key_for_profile, :id | |
has_one :profile | |
end | |
class PmUser < ActiveRecord::Base | |
alias_attribute :primary_key_for_profile, :uuid | |
self.primary_key = :uuid | |
has_one :profile | |
end | |
class ApiUser < ActiveRecord::Base | |
alias_attribute :primary_key_for_profile, :id | |
has_one :profile | |
end | |
class Profile < ActiveRecord::Base | |
belongs_to :user, polymorphic: true, primary_key: :primary_key_for_profile | |
end | |
class BugTest < Minitest::Test | |
def test_pm_profile | |
pm = PmUser.create!(id: "my-uuid-is-this") | |
profile = Profile.new | |
profile.user_id = pm.uuid | |
profile.save! | |
assert_match("my-uuid-is-this", Profile.where(user: pm).to_sql) | |
end | |
def test_app_users | |
app_user = AppUser.create! | |
profile = Profile.new | |
profile.user_id = app_user.id | |
profile.save! | |
assert_match(app_user.id.to_s, Profile.where(user: app_user).to_sql) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment