has_many :through association in rails

 

Refer above figure and the tables physicians, patients and appointments.

This association is often used to set up a many-to-many connection with another model.

1) In Physician model want to mention as follows

class Physician < ActiveRecord::Base

has_many :appointments
has_many :patients, :through => :appointments
end
and we can access Patient as follows

@physicians = Physician.all

<% @physicians.each do |physician| %>

<% physician.patients.each do | patient | %>
<%= patient.name %>,
<% end %>

<% end %>
2) In Patient model want to mention as follows
class Patient < ActiveRecord::Base

has_many :appointments
has_many :physicians, :through => :appointments
end

and we can access Physician as follows
@patients = Patient.all

<% @patients.each do |patient| %>
<% patient.physicians.each do | physician | %>
<%= physician.name %>
<% end %>
<% end %>

3) In Appointent model want to mention as follows

class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end

 

www.klairvoyant.in

 

Advertisements
This entry was posted in rails, ROR, ruby on rails, web development and tagged , , , . Bookmark the permalink.

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 )

Google+ photo

You are commenting using your Google+ 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 )

w

Connecting to %s