Reputation: 9095
I am using http://guides.rubyonrails.org/ to learn ruby & rails. I have problem with joining three tables. , so I made new project as this example: http://guides.rubyonrails.org/association_basics.html#the-has_many_through-association i have three tables physicians, appointments & patients
Models:
physician.rb
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, :through => :appointments
attr_accessible :name
end
appointment.rb
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
attr_accessible :appointment_date, :patient_id, :physician_id
end
patient.rb
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments
attr_accessible :name
end
I want to display the patient name, physician name & appointment_date. how to do this. thanks in advance.
Upvotes: 0
Views: 93
Reputation: 11
In Appointment Controller:
def index
@appointments = Appointment.order("appointment_date DESC")
end
In Appointments#index
<% for appointment in @appointments %>
<%= link_to appointment.patient.name, patients_path(appointment.patient) %>
Appointment for
<%= link_to appointment.physician.name, physician_path(appointment.physician) %>
<% if appointment.appointment_date? %>
<%= appointment.appointment_date %>
<% end %>
<% end %>
Upvotes: 1
Reputation: 1633
I believe, although I am not sure, that you are looking for the way to access objects and their associations in views. Is that correct?
I will give you an example using the Appointment model.
AppointmentsController
class AppointmentsController < ApplicationController
def index
@appointments = Appointment.includes(:physician, :patient).order(:appointment_date)
end
end
appointments#index (Haml syntax)
%ul
- @appointments.each do |appointment|
%li
= appointment.appointment_date
%br
%strong Physician:
= link_to appointment.physician.name, appointment.physician
%br
%strong Patient:
= link_to appointment.patient.name, appointment.patient
This would give you a list of appointments with their dates, physicians, and patients.
Is this the sort of help for which you were looking?
Upvotes: 1