Search code examples
ruby-on-railsrubymodel-associations

How to make associations between 2 tables in Rails


Please help I have two tables:

hospitals
id | name | adress | main_doctor_id

doctors
id | name | contacts | bio | hospital_id

In models:

hospital.rb
has_many :doctors

doctor.rb
belongs_to :hospital

But I need in one more association - each Hospital has one Chief doctor (main_doctor). How to create those association and how get data from Doctors for this main_doctor? ruby 2.0.0p353 Rails 4.0.2


Solution

  • It's quite simple to build main_doctor association:

    class Hospital < ActiveRecord::Base
      has_many :doctors
      belongs_to :main_doctor, :class_name => 'Doctor'
    end