# db/migrate/6_add_foreign_key.rb
class AddForeignKey < ActiveRecord::Migration
def self.up
execute "ALTER TABLE bees ADD CONSTRAINT beehive_id_fkey FOREIGN KEY
(beehive_id) REFERENCES beehives (id);"
end
def self.down
execute "ALTER TABLE bees DROP CONSTRAINT beehive_id_fkey;"
end
end
class AddForeignKey < ActiveRecord::Migration
def self.up
execute "ALTER TABLE user_notes ADD CONSTRAINT creator_id_fkey FOREIGN KEY (creator_id) REFERENCES users (id);"
end
def self.down
execute "ALTER TABLE user_notes DROP CONSTRAINT creator_id_fkey;"
end
end
本文深入探讨了在数据库中实现外键约束的方法,包括如何使用Ruby on Rails的ActiveRecord库来确保数据一致性。详细解释了ALTER TABLE命令如何在特定表中添加外键约束,并引用了具体的代码示例,帮助开发者更好地理解和应用这一关键概念。
725

被折叠的 条评论
为什么被折叠?



