gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 06:59:49 26 4
gpt4 key购买 nike

我有一个表 students,字段为 ward_id,我必须创建一个名为 guardian_users 的表,字段为 id,ward_id,email,guardian_id,hashed_pa​​ssword

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

我如何在 Rails 2.3.5 中做到这一点?

students 表存在,但其他表还不存在。

最佳答案

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

关于ruby-on-rails - 在rails中创建一个表并添加外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5265072/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com