在Rails中创建表并添加外键约束

8
我有一张名为students的表,其中包含字段ward_id,我需要创建一张名为guardian_users的表,它包含字段id,ward_id,email,guardian_id,hashed_password等。

现在我需要添加一个外键约束foreign key。任何对学生表进行的更新/删除/编辑/插入操作都应该同样影响到监护人用户表。

如何在rails 2.3.5中实现这个功能?

学生表已经存在,但另一张表还不存在。


没有问题,但你仍然可以添加注释。 - Kracekumar
应该对其产生相同的影响 - 尝试搜索级联删除。 - Jeff Swensen
@apneadiving:顺便提一下,那是一个相当无用的评论。如果你有这种感觉,为什么要说什么呢? - Josh Glover
2个回答

8

您需要使用 foreign_key_migrations 插件或 #execute 方法。假设您选择使用插件:

class CreateGuardianUsersTable < ActiveRecord::Migration
  def self.up
    create_table(:guardian_users) do |table|
      table.timestamps # I find them useful; YMMV
      table.integer :guardian_id
      table.integer :ward_id, :null => false, :references => [:students, :id]
      table.string :email
      table.string :heahead_password
    end
  end

  def self.down
    drop_table :guardian_users
  end
end

在你的模型中:

class GuardianUser < ActiveRecord::Base
  belongs_to :student
end

class Student < ActiveRecord::Base
  has_many guardian_users:, :foreign_key => 'ward_id', :class_name => 'GuardianUser', :dependent => :destroy
end

-2

你需要先生成迁移以建立 guardian_users 表。你可以从 Rails 文档中了解有关迁移和外键的知识。你还需要使用 has_many 或 belongs_to 等方法将代表这两个实体的任何模型进行关联。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接