创建一个表,并添加外键约束

问题描述:

我有一个表students与现场ward_id,我要创建一个带有字段id,ward_idemailguardian_idhashed_password创建一个表,并添加外键约束

现在我必须添加一个名为guardian_users表约束条件foreign key。学生的任何更新/删除/编辑/插入应该对guardian_users具有相同的效果。

如何在rails 2.3.5中做到这一点?

表学生存在,但其他人不存在。

+0

没有问题,但你仍然可以发表评论 – Kracekumar 2011-03-10 20:30:49

+0

“应该有相同的效果” - 尝试搜索级联删除。 – 2011-03-10 22:03:16

+0

@apneadiving:仅供参考,这是一个相当无用的评论。如果你有这种感觉,为什么要说什么? – 2011-03-25 09:50:43

您将需要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 
+0

这就是我所发现的,对的,谢谢。 – Kracekumar 2011-03-26 03:59:29

您将不得不首先生成您的迁移以构建guardian_users表。您可以阅读来自Rails文档的迁移并完成FK的迁移。您还需要将表示这两个实体的任何模型与has_many或belongs_to之类的内容关联起来。