Skip to content

Commit

Permalink
refactor: database migration for primary and foreign key error
Browse files Browse the repository at this point in the history
  • Loading branch information
nejdetkadir committed May 30, 2023
1 parent a6e87f4 commit c7e6516
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 19 deletions.
2 changes: 1 addition & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
devise-api (0.0.0)
devise-api (0.1.1)
devise (>= 4.7.2)
dry-configurable (~> 1.0, >= 1.0.1)
dry-initializer (>= 3.1.1)
Expand Down
16 changes: 0 additions & 16 deletions lib/devise/api/generators/install_generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,22 +40,6 @@ def locale_destination
def migration_version
"[#{ActiveRecord::VERSION::MAJOR}.#{ActiveRecord::VERSION::MINOR}]"
end

def primary_key_type
fallback = :integer

begin
ActiveRecord::Base.connection.supports_pgcrypto_uuid? ? :uuid : fallback
rescue StandardError
fallback
end
end

def table_defaults_for_primary_key_type
return ', type: :uuid' if primary_key_type == :uuid

''
end
end
end
end
Expand Down
17 changes: 15 additions & 2 deletions lib/devise/api/generators/templates/migration.rb.erb
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@

class CreateDeviseApiTables < ActiveRecord::Migration<%= migration_version %>
def change
create_table :devise_api_tokens<%= table_defaults_for_primary_key_type %> do |t|
t.belongs_to :resource_owner, null: false<%= table_defaults_for_primary_key_type %>, polymorphic: true, index: true
# Use Active Record's configured type for primary and foreign keys
primary_key_type, foreign_key_type = primary_and_foreign_key_types

create_table :devise_api_tokens, id: primary_key_type do |t|
t.belongs_to :resource_owner, null: false, polymorphic: true, index: true, type: foreign_key_type
t.string :access_token, null: false, index: true
t.string :refresh_token, null: true, index: true
t.integer :expires_in, null: false
Expand All @@ -13,4 +16,14 @@ class CreateDeviseApiTables < ActiveRecord::Migration<%= migration_version %>
t.timestamps
end
end

private

def primary_and_foreign_key_types
config = Rails.configuration.generators
setting = config.options[config.orm][:primary_key_type]
primary_key_type = setting || :primary_key
foreign_key_type = setting || :bigint
[primary_key_type, foreign_key_type]
end
end

0 comments on commit c7e6516

Please sign in to comment.