mirror of
https://github.com/rails/rails.git
synced 2022-11-09 12:12:34 -05:00
fk: :primary_key
option for non-standard pk's.
This commit is contained in:
parent
1c170fdea2
commit
a48b675d54
3 changed files with 25 additions and 3 deletions
|
@ -647,9 +647,11 @@ module ActiveRecord
|
|||
end
|
||||
|
||||
def add_foreign_key(from_table, to_table, options = {})
|
||||
primary_key = options.fetch(:primary_key, "id")
|
||||
|
||||
options = {
|
||||
column: options.fetch(:column),
|
||||
primary_key: "id",
|
||||
primary_key: primary_key,
|
||||
name: foreign_key_name(from_table, options)
|
||||
}
|
||||
at = create_alter_table from_table
|
||||
|
|
|
@ -1,9 +1,12 @@
|
|||
require 'cases/helper'
|
||||
require 'support/ddl_helper'
|
||||
|
||||
if ActiveRecord::Base.connection.supports_foreign_keys?
|
||||
module ActiveRecord
|
||||
class Migration
|
||||
class ForeignKeyTest < ActiveRecord::TestCase
|
||||
include DdlHelper
|
||||
|
||||
class Rocket < ActiveRecord::Base
|
||||
end
|
||||
|
||||
|
@ -55,6 +58,23 @@ module ActiveRecord
|
|||
assert_equal "astronauts_rocket_id_fk", fk.name
|
||||
end
|
||||
|
||||
def test_add_foreign_key_with_non_standard_primary_key
|
||||
with_example_table @connection, "space_shuttles", "pk integer PRIMARY KEY" do
|
||||
@connection.add_foreign_key(:astronauts, :space_shuttles,
|
||||
column: "rocket_id", primary_key: "pk", name: "custom_pk")
|
||||
|
||||
foreign_keys = @connection.foreign_keys("astronauts")
|
||||
assert_equal 1, foreign_keys.size
|
||||
|
||||
fk = foreign_keys.first
|
||||
assert_equal "astronauts", fk.from_table
|
||||
assert_equal "space_shuttles", fk.to_table
|
||||
assert_equal "pk", fk.primary_key
|
||||
|
||||
@connection.remove_foreign_key :astronauts, name: "custom_pk"
|
||||
end
|
||||
end
|
||||
|
||||
def test_remove_foreign_key
|
||||
@connection.add_foreign_key :astronauts, :rockets, column: "rocket_id"
|
||||
|
||||
|
|
|
@ -1,8 +1,8 @@
|
|||
module DdlHelper
|
||||
def with_example_table(connection, table_name, definition = nil)
|
||||
connection.exec_query("CREATE TABLE #{table_name}(#{definition})")
|
||||
connection.execute("CREATE TABLE #{table_name}(#{definition})")
|
||||
yield
|
||||
ensure
|
||||
connection.exec_query("DROP TABLE #{table_name}")
|
||||
connection.execute("DROP TABLE #{table_name}")
|
||||
end
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue