0

Let's say I have

class CreateAppointments < ActiveRecord::Migration
  def change
    create_table :physicians do |t|
      t.string :name
      t.timestamps null: false
    end

    create_table :patients do |t|
      t.string :name
      t.timestamps null: false
    end

    create_table :appointments do |t|
      t.belongs_to :physician, index: true
      t.belongs_to :patient, index: true
      t.datetime :appointment_date
      t.timestamps null: false
    end
  end
end

1- Do I have to define again the associations on the model file? which leads me to my next question.... 2- Do I have to create a model for this third table of appointments or just run the migration and the Active Record will take care of updating it everytime a doctor and a patient updates? when will the insert to this third table will be triggered in this type of association?

dwenzel
  • 1,404
  • 9
  • 15
JAF
  • 350
  • 3
  • 19
  • Take a look at code gnome's answer here: https://stackoverflow.com/questions/11600928/when-should-one-use-a-has-many-through-relation-in-rails – bbozo Jan 02 '16 at 19:26

1 Answers1

1

There is alot of magic inside of active record, so i understand where you are coming from.

  1. Yes, The migration will not add the proper associations to your ActiveRecord models. Migrations are there to make changes to the database.

  2. Yes, if you did not generate this using rails g scaffold or model, then you will need to create an Appointment class that inherits from ActiveRecord::Base in order to work with it through the orm. Then put the proper associations on them (patients have many appointments, they would also have many doctors through appointments. vice versa for doctors.

Austio
  • 5,939
  • 20
  • 34
  • so - we need to first create the model and then create the migration. this is because the generate command cannot handle associations as of now. right ? – mrtechmaker Sep 05 '19 at 12:18
  • @KaranAhuja you can generate the join tables using generate with the `references` keyword. Please check the rails guides for exact syntax https://guides.rubyonrails.org/active_record_migrations.html – Austio Sep 05 '19 at 19:49