开发者

Create a table in rails and add foreign key constraint

开发者 https://www.devze.com 2023-02-15 22:08 出处:网络
I have a table students with field ward_id and I have to create a table named guardian_users with fields id,ward_id,email,g开发者_开发技巧uardian_id,hashed_password etc.

I have a table students with field ward_id and I have to create a table named guardian_users with fields id,ward_id,email,g开发者_开发技巧uardian_id,hashed_password etc.

Now I have to add constraint foreign key. Any update/delete/edit/insertion in students should have same effect on guardian_users.

How can I do that in rails 2.3.5?

Table students exists but other one doesn't exist yet.


You'll either need the foreign_key_migrations plugin or the #execute method. Assuming you go with the plugin:

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

And in your models:

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


You're going to have to generate your migration first to build the guardian_users table. You can read up on migrations from the rails docs and doing FK's. You will also need to associate any models that represent the two of these entities with things like has_many or belongs_to.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号