Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

fk: `:primary_key` option for non-standard pk's.

  • Loading branch information...
commit a48b675d54101b048228d1011ffa426c2b7fe94d 1 parent 1c170fd
@senny senny authored
View
4 activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
@@ -647,9 +647,11 @@ def foreign_keys(table_name)
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
View
20 activerecord/test/cases/migration/foreign_key_test.rb
@@ -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 @@ def test_add_foreign_key
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"
View
4 activerecord/test/support/ddl_helper.rb
@@ -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
Please sign in to comment.
Something went wrong with that request. Please try again.