Skip to content

Instantly share code, notes, and snippets.

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 jinhucheung/45fb4b2116095aca0881bed63dcee4a5 to your computer and use it in GitHub Desktop.
Save jinhucheung/45fb4b2116095aca0881bed63dcee4a5 to your computer and use it in GitHub Desktop.
Mixed typed polymorphic keys
# 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 :pm_users, force: true do |t|
t.string :uuid
end
create_table :app_users, id: :string, force: true do |t|
end
create_table :api_users, id: :string, force: true do |t|
end
create_table :profiles, force: true do |t|
t.string :user_id
t.string :user_type
end
end
class PmUser < ActiveRecord::Base
alias_attribute :primary_key_for_profile, :uuid
has_one :profile
end
class AppUser < ActiveRecord::Base
alias_attribute :primary_key_for_profile, :id
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_user = PmUser.create!(uuid: uuid)
profile = Profile.create!(user_type: 'PmUser', user_id: uuid)
assert_equal(uuid, pm_user.uuid)
assert_match(uuid, Profile.where(user: pm_user).to_sql)
end
def test_app_users
app_user = AppUser.create!(id: uuid)
profile = Profile.create!(user_type: 'AppUser', user_id: uuid)
assert_equal(uuid, app_user.id)
assert_match(app_user.id.to_s, Profile.where(user: app_user).to_sql)
end
def uuid
'264e1067-1d4f-4f1d-99b1-8f0689ba1add'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment