Permalink
Browse files

raise `ArgumentError` when redefining the primary key column. Closes #…

  • Loading branch information...
1 parent b104157 commit e4790a2c5b99704f430c837d8f22fec418f2c8af @senny senny committed Oct 28, 2012
@@ -1,5 +1,10 @@
## Rails 4.0.0 (unreleased) ##
+* The `create_table` method raises an `ArgumentError` when the primary key column is redefined.
+ Fix #6378
+
+ *Yves Senn*
+
* `ActiveRecord::AttributeMethods#[]` raises `ActiveModel::MissingAttributeError`
error if the given attribute is missing. Fixes #5433.
@@ -234,6 +234,10 @@ def column(name, type, options = {})
name = name.to_s
type = type.to_sym
+ if primary_key_column_name == name
+ raise ArgumentError, "you can't redefine the primary key column '#{name}'. To define a custom primary key, pass { id: false } to create_table."
+ end
+
column = self[name] || new_column_definition(@base, name, type)
limit = options.fetch(:limit) do
@@ -302,6 +306,11 @@ def new_column_definition(base, name, type)
definition
end
+ def primary_key_column_name
+ primary_key_column = columns.detect { |c| c.type == :primary_key }
+ primary_key_column && primary_key_column.name
+ end
+
def native
@base.native_database_types
end
@@ -132,6 +132,26 @@ def test_create_table_with_primary_key_prefix_as_table_name
assert_equal %w(foo testingid), connection.columns(:testings).map(&:name).sort
end
+ def test_create_table_raises_when_redefining_primary_key_column
+ error = assert_raise(ArgumentError) do
+ connection.create_table :testings do |t|
+ t.column :id, :string
+ end
+ end
+
+ assert_equal "you can't redefine the primary key column 'id'. To define a custom primary key, pass { id: false } to create_table.", error.message
+ end
+
+ def test_create_table_raises_when_redefining_custom_primary_key_column
+ error = assert_raise(ArgumentError) do
+ connection.create_table :testings, primary_key: :testing_id do |t|
+ t.column :testing_id, :string
+ end
+ end
+
+ assert_equal "you can't redefine the primary key column 'testing_id'. To define a custom primary key, pass { id: false } to create_table.", error.message
+ end
+
def test_create_table_with_timestamps_should_create_datetime_columns
connection.create_table table_name do |t|
t.timestamps

0 comments on commit e4790a2

Please sign in to comment.