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.
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 ...
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With