Posted By

ctran on 08/21/06


Tagged

rails migration


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

episod
dapan
webstic


foreign_key_migration.rb


 / Published in: Ruby
 

Add foreign key support for migration

  1. module ForeignKeyMigration
  2. module AbstractAdapter
  3. # Add foreign-key constraints when creating tables. It uses SQL-92 syntax and as such should be
  4. # compatible with most databases that support foreign-key constraints. By default,
  5. # the constraint is named "fk_table_a_on_table_b
  6. #
  7. # ===== Examples
  8. # Add a foreign key to movie_crews (person_id) that references people table (id)
  9. # add_foreign_key :movie_crews, :person_id, :people
  10. #
  11. # Specify the referenced columns
  12. # add_foreign_key :movie_crews, :person_id, :people, :id
  13. #
  14. # Multiple columns
  15. # add_foreign_key :movie_crews, [:person_id, :role], :people, [:id, :role]
  16. #
  17. # Add a foreign key with a name
  18. # add_foreign_key :movie_crews, :person_id, :people, :id, :name => 'movie_crews_xref_people'
  19. #
  20. def add_foreign_key(foreign_table_name, foreign_column_names, primary_table_name, primary_column_names = :id, options = {})
  21. foreign_column_names = Array(foreign_column_names).join(", ")
  22. primary_column_names = Array(primary_column_names).join(", ")
  23. fk_name = options[:name] || fk_name(foreign_table_name, foreign_column_names, primary_table_name, primary_column_names)
  24. execute "ALTER TABLE #{foreign_table_name} ADD CONSTRAINT #{fk_name} FOREIGN KEY (#{foreign_column_names}) REFERENCES #{primary_table_name} (#{primary_column_names})"
  25. end
  26.  
  27. # Remove a foreign key constraint
  28. #
  29. # ==== Examples
  30. # ===== Remove the fk 'fk_user_role_user' from 'users_roles' table
  31. # remove_foreign_key :users_roles, :fk_users_roles_user
  32. #
  33. # ===== Remove the fk on comments (post_id) reference posts (id)
  34. # remove_foreign_key :comments, :post_id, :posts
  35. #
  36. def remove_foreign_key(foreign_table_name, fk_name, primary_table_name = nil, primary_column_names = nil)
  37. primary_column_names = :id unless primary_column_names
  38. fk_name = fk_name(foreign_table_name, fk_name, primary_table_name, primary_column_names) if primary_table_name
  39. execute "ALTER TABLE #{foreign_table_name.to_s} DROP FOREIGN KEY #{fk_name.to_s}"
  40. end
  41.  
  42. def fk_name(foreign_table_name, foreign_column_names, primary_table_name, primary_column_names)
  43. "fk_#{foreign_table_name.to_s}_on_#{primary_table_name.to_s}"
  44. end
  45. end
  46. end

Report this snippet  

You need to login to post a comment.