Skip to content

Commit b623494

Browse files
authored
Merge pull request rails#45685 from adrianna-chang-shopify/ac-build-create-join-table-definition
Extract `#build_create_join_table_definition`
2 parents 214cd77 + 108c30e commit b623494

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -385,6 +385,24 @@ def create_join_table(table_1, table_2, column_options: {}, **options)
385385
end
386386
end
387387

388+
# Builds a TableDefinition object for a join table.
389+
#
390+
# This definition object contains information about the table that would be created
391+
# if the same arguments were passed to #create_join_table. See #create_join_table for
392+
# information about what arguments should be passed.
393+
def build_create_join_table_definition(table_1, table_2, column_options: {}, **options) # :nodoc:
394+
join_table_name = find_join_table_name(table_1, table_2, options)
395+
column_options.reverse_merge!(null: false, index: false)
396+
397+
t1_ref, t2_ref = [table_1, table_2].map { |t| reference_name_for_table(t) }
398+
399+
build_create_table_definition(join_table_name, **options.merge!(id: false)) do |td|
400+
td.references t1_ref, **column_options
401+
td.references t2_ref, **column_options
402+
yield td if block_given?
403+
end
404+
end
405+
388406
# Drops the join table specified by the given arguments.
389407
# See #create_join_table and #drop_table for details.
390408
#

activerecord/test/cases/migration/schema_definitions_test.rb

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,28 @@ def test_build_create_table_definition_without_block
3636
assert id_column.sql_type
3737
end
3838

39+
def test_build_create_join_table_definition_with_block
40+
assert connection.table_exists?(:posts)
41+
assert connection.table_exists?(:comments)
42+
43+
join_td = connection.build_create_join_table_definition(:posts, :comments) do |t|
44+
t.column :another_col, :string
45+
end
46+
47+
assert_equal :comments_posts, join_td.name
48+
assert_equal ["another_col", "comment_id", "post_id"], join_td.columns.map(&:name).sort
49+
end
50+
51+
def test_build_create_join_table_definition_without_block
52+
assert connection.table_exists?(:posts)
53+
assert connection.table_exists?(:comments)
54+
55+
join_td = connection.build_create_join_table_definition(:posts, :comments)
56+
57+
assert_equal :comments_posts, join_td.name
58+
assert_equal ["comment_id", "post_id"], join_td.columns.map(&:name).sort
59+
end
60+
3961
def test_build_create_index_definition
4062
connection.create_table(:test) do |t|
4163
t.column :foo, :string

0 commit comments

Comments
 (0)