ruby-on-rails – 在rails中创建一个表并添加外键约束

我有一个带有field ward_id的表学生,我必须创建一个名为guardian_users的表,其中包含字段id,ward_id,email,guardian_id,hashed_pa​​ssword等.

现在我必须添加约束外键.学生中的任何更新/删除/编辑/插入都应对guardian_users产生相同的影响.

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

表学生存在但其他人尚不存在.

解决方法

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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...