Extract build_create_join_table_definition
Exposes an API for building a TableDefinition for a join table operation.
This commit is contained in:
parent
6d100e540e
commit
108c30e114
@ -385,6 +385,24 @@ def create_join_table(table_1, table_2, column_options: {}, **options)
|
||||
end
|
||||
end
|
||||
|
||||
# Builds a TableDefinition object for a join table.
|
||||
#
|
||||
# This definition object contains information about the table that would be created
|
||||
# if the same arguments were passed to #create_join_table. See #create_join_table for
|
||||
# information about what arguments should be passed.
|
||||
def build_create_join_table_definition(table_1, table_2, column_options: {}, **options) # :nodoc:
|
||||
join_table_name = find_join_table_name(table_1, table_2, options)
|
||||
column_options.reverse_merge!(null: false, index: false)
|
||||
|
||||
t1_ref, t2_ref = [table_1, table_2].map { |t| reference_name_for_table(t) }
|
||||
|
||||
build_create_table_definition(join_table_name, **options.merge!(id: false)) do |td|
|
||||
td.references t1_ref, **column_options
|
||||
td.references t2_ref, **column_options
|
||||
yield td if block_given?
|
||||
end
|
||||
end
|
||||
|
||||
# Drops the join table specified by the given arguments.
|
||||
# See #create_join_table and #drop_table for details.
|
||||
#
|
||||
|
@ -36,6 +36,28 @@ def test_build_create_table_definition_without_block
|
||||
assert id_column.sql_type
|
||||
end
|
||||
|
||||
def test_build_create_join_table_definition_with_block
|
||||
assert connection.table_exists?(:posts)
|
||||
assert connection.table_exists?(:comments)
|
||||
|
||||
join_td = connection.build_create_join_table_definition(:posts, :comments) do |t|
|
||||
t.column :another_col, :string
|
||||
end
|
||||
|
||||
assert_equal :comments_posts, join_td.name
|
||||
assert_equal ["another_col", "comment_id", "post_id"], join_td.columns.map(&:name).sort
|
||||
end
|
||||
|
||||
def test_build_create_join_table_definition_without_block
|
||||
assert connection.table_exists?(:posts)
|
||||
assert connection.table_exists?(:comments)
|
||||
|
||||
join_td = connection.build_create_join_table_definition(:posts, :comments)
|
||||
|
||||
assert_equal :comments_posts, join_td.name
|
||||
assert_equal ["comment_id", "post_id"], join_td.columns.map(&:name).sort
|
||||
end
|
||||
|
||||
def test_build_create_index_definition
|
||||
connection.create_table(:test) do |t|
|
||||
t.column :foo, :string
|
||||
|
Loading…
Reference in New Issue
Block a user