Skip to content

Rails Associations(Active Record)

09/03/2011

hi today Mr.thiyagarajan took class about associations and showed live demo of set association between the models.

we saw two associations today
has_and_belongs_to_many
has_many :through

has_and_belongs_to_many:
we take example as Doctor and clinic.
Relation: In a clinic has many Doctors working and same as A Doctor has working with many Clinic.here both relations are many to many relations.
Connection: To connect both Doctor and Clinic many to many relationship need one connection model. It may ClinicDoctos model. It is a bridge table.

create model clinic and set relations

app/model/clinic.rb


class Clinic < ActiveRecord::Base
 has_and_belongs_to_many :doctors
end

create model Doctor and set relation

app/model/doctor.rb


class Doctor < ActiveRecord::Base
 has_and_belongs_to_many :clinics
end

Create the migration table to connect both Doctor and Clinic.This table should not have id and other except connection model id.

$rails g migration clinics_doctors_join

db/migration/……clinics_doctors_join.rb


class ClinicDoctorMigration < ActiveRecord::Migration
 def self.up
 create_table :clinics_doctors_join, :id => false  do |t|
 t.integer :clinic_id
 t.integer :doctor_id
 t.timestamps
 end
 end

 def self.down
 end
end

has_many :through

we take example Medical Represendative(MSR),Doctor and Tourplane schedule
Relation:MSRs meet the Doctors via Tourplanner schdular.In a company has many MSR.
Connection:tourplanner is a connector both doctor and msr.both doctor and msr has many
tourplanner but tourplanner only blongs to both doctor and msr.

generate Msr model
app/model/msr.rb

class Msr < ActiveRecord::Base
has_many :tourplanes
has_many :doctors, :through => :tourplanes
end

generate Doctor model
app/model/doctor.rb

class Doctor < ActiveRecord::Base
has_many :tourplanes
has_many :doctors, :through => :tourplanes
end

generate tourplaner model
this through provides id field and some additional fields and also made changes in future.
This is differ from has_and_belongs_to_many
$ rails g Tourplane msr_id:integer doctor_id:integer description:string

app/model/Tourplane.rb

class Tourplane < ActiveRecord::Base
 belongs_to :msr
 belongs_to :doctor
end

thanks….

Advertisements

From → Rails

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: