Skip to content

Commit

Permalink
Add foreign key options to safe_add_reference (#238)
Browse files Browse the repository at this point in the history
  • Loading branch information
chaadow authored Sep 8, 2023
1 parent fa43564 commit 405b3ba
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
7 changes: 4 additions & 3 deletions lib/strong_migrations/safe_methods.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,11 +29,12 @@ def safe_add_reference(table, reference, *args, **options)
else
(ActiveRecord::Base.pluralize_table_names ? reference.to_s.pluralize : reference).to_sym
end


foreign_key_opts = foreign_key.is_a?(Hash) ? foreign_key.except(:to_table) : {}
if reference
@migration.add_foreign_key(table, name, column: "#{reference}_id")
@migration.add_foreign_key(table, name, column: "#{reference}_id", **foreign_key_opts)
else
@migration.add_foreign_key(table, name)
@migration.add_foreign_key(table, name, **foreign_key_opts)
end
end
end
Expand Down
6 changes: 6 additions & 0 deletions test/migrations/add_reference.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ def change
end
end

class AddReferenceForeignKeyOnDelete < TestMigration
def change
add_reference :users, :device, foreign_key: {on_delete: :nullify}, index: false
end
end

class AddReferenceConcurrently < TestMigration
disable_ddl_transaction!

Expand Down
4 changes: 4 additions & 0 deletions test/safe_by_default_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,10 @@ def test_add_reference_foreign_key_to_table
assert_safe AddReferenceForeignKeyToTable
end

def test_add_reference_foreign_key_on_delete
assert_safe AddReferenceForeignKeyOnDelete
end

def test_add_reference_extra_arguments
assert_argument_error AddReferenceExtraArguments
end
Expand Down

0 comments on commit 405b3ba

Please sign in to comment.