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

前端之家收集整理的这篇文章主要介绍了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方法.假设你使用插件
  1. class CreateGuardianUsersTable < ActiveRecord::Migration
  2. def self.up
  3. create_table(:guardian_users) do |table|
  4. table.timestamps # I find them useful; YMMV
  5. table.integer :guardian_id
  6. table.integer :ward_id,:null => false,:references => [:students,:id]
  7. table.string :email
  8. table.string :heahead_password
  9. end
  10. end
  11.  
  12. def self.down
  13. drop_table :guardian_users
  14. end
  15. end

在你的模型中:

  1. class GuardianUser < ActiveRecord::Base
  2. belongs_to :student
  3. end
  4.  
  5. class Student < ActiveRecord::Base
  6. has_many guardian_users:,:foreign_key => 'ward_id',:class_name => 'GuardianUser',:dependent => :destroy
  7. end

猜你在找的Ruby相关文章