SUPPORT THE SITE WITH A CLICK

Subscribe Rss:

SUPPORT THE SITE WITH A CLICK

Saturday, March 8, 2008

Adding mysql foreign key constraint using ruby on rails migrations

Hi i am new to ruby on rails.As per the Agile Development pdf i used to create my table using migrations,when i tried to create foreign key constraint i find difficult to do this,and i got so many errors.Finally i got the solution what i did is
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

1 comment :