提交 5a14349b 编写于 作者: Y Yves Senn

`:to_table` when adding a fk through `add_reference`.

Closes #21563.

The `name` argument of `add_references` was both used to generate the
column name `<name>_id` and as the target table for the foreign key
`name.pluralize`.

It's primary purpose is to define the column name. In cases where the
`to_table` of the foreign key is different than the column name we
should be able to specify it individually.
上级 256097cb
* Make it possible to pass `:to_table` when adding a foreign key through
`add_reference`.
Fixes #21563.
*Yves Senn*
* No longer pass depreacted option `-i` to `pg_dump`.
*Paul Sadauskas*
......
......@@ -123,23 +123,29 @@ def index_options
end
def foreign_key_options
as_options(foreign_key)
as_options(foreign_key).merge(column: column_name)
end
def columns
result = [["#{name}_id", type, options]]
result = [[column_name, type, options]]
if polymorphic
result.unshift(["#{name}_type", :string, polymorphic_options])
end
result
end
def column_name
"#{name}_id"
end
def column_names
columns.map(&:first)
end
def foreign_table_name
Base.pluralize_table_names ? name.to_s.pluralize : name
foreign_key_options.fetch(:to_table) do
Base.pluralize_table_names ? name.to_s.pluralize : name
end
end
end
......
......@@ -724,6 +724,10 @@ def index_name_exists?(table_name, index_name, default)
#
# add_reference(:products, :supplier, foreign_key: true)
#
# ====== Create a supplier_id column and a foreign key to the firms table
#
# add_reference(:products, :supplier, foreign_key: {to_table: :firms})
#
def add_reference(table_name, *args)
ReferenceDefinition.new(*args).add_to(update_table_definition(table_name, self))
end
......
......@@ -53,6 +53,15 @@ class ReferencesForeignKeyTest < ActiveRecord::TestCase
assert_equal "other_id", fk.primary_key
end
test "to_table option can be passed" do
@connection.create_table :testings do |t|
t.references :parent, foreign_key: { to_table: :testing_parents }
end
fks = @connection.foreign_keys("testings")
assert_equal([["testings", "testing_parents", "parent_id"]],
fks.map {|fk| [fk.from_table, fk.to_table, fk.column] })
end
test "foreign keys cannot be added to polymorphic relations when creating the table" do
@connection.create_table :testings do |t|
assert_raises(ArgumentError) do
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册