Skip to content

Commit

Permalink
Overrides #reset_primary_key to modify @primary_key.
Browse files Browse the repository at this point in the history
ar-multitenant expects that #primary_key returns single column instead of composite primary_keys for backward compatibilities.

Previously overwriting #primary_key to return single pk, but since the timing for
writing @primary_key has changed since Rails 7.2, this way is no longer available.
Instead, overwriting `#reset_primary_key`, which handles calculating `@primary_key`.
  • Loading branch information
alpaca-tc committed Aug 21, 2024
1 parent b81b63b commit ff19aab
Showing 1 changed file with 7 additions and 12 deletions.
19 changes: 7 additions & 12 deletions lib/activerecord-multi-tenant/model_extensions.rb
Original file line number Diff line number Diff line change
Expand Up @@ -42,20 +42,15 @@ def partition_key
.try(:instance_variable_get, :@partition_key)
end

# Avoid primary_key errors when using composite primary keys (e.g. id, tenant_id)
def primary_key
if defined?(PRIMARY_KEY_NOT_SET) ? !PRIMARY_KEY_NOT_SET.equal?(@primary_key) : @primary_key
return @primary_key
end

def reset_primary_key
primary_object_keys = Array.wrap(connection.schema_cache.primary_keys(table_name)) - [partition_key]

@primary_key = if primary_object_keys.size == 1
primary_object_keys.first
elsif table_name &&
connection.schema_cache.columns_hash(table_name).include?(DEFAULT_ID_FIELD)
DEFAULT_ID_FIELD
end
self.primary_key = if primary_object_keys.size == 1
primary_object_keys.first
elsif table_name &&
connection.schema_cache.columns_hash(table_name).include?(DEFAULT_ID_FIELD)
DEFAULT_ID_FIELD
end
end

def inherited(subclass)
Expand Down

0 comments on commit ff19aab

Please sign in to comment.