在rails中创建一个表并添加外键约束

时间:2011-03-10 19:50:00

标签: ruby-on-rails ruby activerecord

我有一个表students,其中包含字段ward_id,我必须创建一个名为guardian_users的表格,其中包含字段id,ward_idemail,{{1} },guardian_id等。

现在我必须添加约束hashed_password。学生中的任何更新/删除/编辑/插入都应对guardian_users产生相同的效果。

我怎么能在rails 2.3.5中做到这一点?

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:-2)

您必须首先生成迁移以构建guardian_users表。您可以从rails docs和FK中了解迁移。您还需要将代表这两个实体的任何模型与has_many或belongs_to相关联。