Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a table in rails and add foreign key constraint

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,guardian_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.

like image 595
Kracekumar Avatar asked Mar 10 '11 19:03

Kracekumar


People also ask

How do I add a foreign key reference in rails?

Now, if you use the special generator syntax for migrations, Rails 4.2 will automatically create the correct migration with foreign key constraints included. rails g migration AddUserToUploads user:references produces add_reference :uploads, :user, index: true, foreign_key: true in the appropriate migration. Use ...

How would you add a foreign key constraint?

To create a SQL foreign key constraint, the parent table should have primary key column or column with UNIQUE constraint. In this case, table Dept is parent table which has Primary key and will be referenced in child tables having foreign key.

Do you need foreign keys in rails?

Foreign keys ensure consistency between related database tables. The current database review process always encourages you to add foreign keys when creating tables that reference records from other tables. Starting with Rails version 4, Rails includes migration helpers to add foreign key constraints to database tables.


1 Answers

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
like image 196
Josh Glover Avatar answered Nov 15 '22 05:11

Josh Glover