0

I have this table structure:

class CreateUsers < ActiveRecord::Migration
  def change
    create_table :users do |t|
      t.string :username 
      t.string :email
      t.string :encrypted_password 
      t.string :salt
      t.timestamps
    end
  end
end

And I want to add a new table as shown below:

class CreateHolidays < ActiveRecord::Migration
  def change
    create_table :holidays do |t|
      t.string :earn_leave
      t.string :seek_leave
      t.string :unplanned_leave
      t.timestamps
      t.timestamps
    end
    add_index(users,id)
  end
end

What should I do for this, please also suggest commands that can/should be used for migration.

1 Answers1

0

You want to look up about foreign_keys:

#app/models/holiday.rb
class Holiday < ActiveRecord::Base
   belongs_to :user
end

#app/models/user.rb
class User < ActiveRecord::Base
   has_many :holidays
end

This will mean you have to add the user_id foreign key to your holidays data table:

class CreateHolidays < ActiveRecord::Migration
  def change
    create_table :holidays do |t|
      t.references :user 
      t.string :earn_leave
      t.string :seek_leave
      t.string :unplanned_leave
      t.timestamps
      t.timestamps
    end
  end
end

You must remember that Rails is designed to be built on top of a relational database. As such, it uses foreign_keys in the tables to locate associated records:

enter image description here

The above will allow you to call:

@user.holidays

and

@holiday.user
Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147