I tried the following
remove_foreign_key :users, :asset_types, column: :seek_asset_type_id
But got the error
StandardError: An error has occurred, this and all later migrations canceled:
wrong number of arguments (given 3, expected 1..2)
The documentation says it uses the same options as #add_foreign_key
.
Documentation
The column was created previously with
add_reference :users, :seek_asset_type, foreign_key: {to_table: :asset_types}
This is the definition:
"fk_rails_4dcaa1c59c" FOREIGN KEY (seek_asset_type_id) REFERENCES asset_types(id)
A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.
We want to remove the foreign key named fk_student_city_id from the table student. To drop a foreign key from a table, use the ALTER TABLE clause with the name of the table (in our example, student) followed by the clause DROP CONSTRAINT with the name of the foreign key constraint. In our example, the name of this constraint is fk_student_city_id.
You want to drop a foreign key from a table in a database. We want to remove the foreign key named fk_student_city_id from the table student. To drop a foreign key from a table, use the ALTER TABLE clause with the name of the table (in our example, student) followed by the clause DROP CONSTRAINT with the name of the foreign key constraint.
A Foreign key is an attribute in one table which takes references from another table where it acts as the primary key in that table. Also, the column acting as a foreign key should be present in both tables.
Step 1 : Drop the Primary key of the table. Step 2 : Now it will prompt whether to delete all the foreign references or not. Step 3 : Delete the table. You have to drop the constraint before drop your table. You can use those queries to find all FKs in your table and find the FKs in the tables in which your table is used.
Use revert
:
def change
revert do
add_reference :users, :seek_asset_type, foreign_key: { to_table: :asset_types }
end
end
Another way is to revert a migration by its name:
def change
revert AddAssetTypeReferenceToUsers
# I made up this migration name,
# so please fill in the appropriate name
end
This seems to be a deficiency in remove_foreign_key
, but you can work around it by defining an add_foreign_key
inverse action using reversible
:
reversible do |dir|
dir.up do
remove_foreign_key :users, column: :seek_asset_type
end
dir.down do
add_foreign_key :users, :asset_types, column: :seek_asset_type
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With