1.First i create a migration file in the terminal using the command
ruby script/generate migration id_foreign_keys
exists db/migrate
create db/migrate/008_id_foreign_keys.rb
2.Then edit the 008_id_foreign_keys.rb file
At first it will be like
class IdForeignKeys < ActiveRecord::Migration
def self.up
end
def self.down
end
end
We have to write the query in def self.up
execute "ALTER TABLE subcitymenus add constraint sub_city_menu FOREIGN
KEY(referid) REFERENCES citymenus(id) ON DELETE CASCADE"
3.finally my 008_id_foreign_keys.rb file will look like this
class IdForeignKeys < ActiveRecord::Migration
def self.up
execute "ALTER TABLE subcitymenus add constraint sub_city_menu FOREIGN KEY(referid)
REFERENCES citymenus(id) ON DELETE CASCADE"
end
def self.down
end
end
4.Then go for migration
rake db:migrate
5.Finally it will show in the terminal like this
== 8 IdForeignKeys: migrating =================================================
-- execute("ALTER TABLE subcitymenus add constraint sub_city_menu FOREIGN KEY(re
ferid)\n REFERENCES citymenus(id) ON DELETE CASCADE")
-> 0.2040s
== 8 IdForeignKeys: migrated (0.2040s) ========================================
6.Now You can check in your mysql using mysql query browser or any other tool
7.This how i have solved the foreign key constraint in mysql using rake
you can now use add_foreign_key_constraints
ReplyDelete