2013-09-23 101 views
0

我使用http://guides.rubyonrails.org/來學習ruby &導軌。我在加入三張桌子時遇到問題。 ,所以我做了新的項目,因爲這例子:http://guides.rubyonrails.org/association_basics.html#the-has_many_through-association我有三個表醫生,預約&患者在Rails3中加入三張表

型號:

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 

我想顯示患者姓名,醫師姓名& appointment_date。這個怎麼做。 在此先感謝。

+0

你有這些模型建立的控制器和視圖? –

+0

是的,我擁有所有三種型號的控制器和視圖。 –

+0

那麼,你只是想知道如何訪問視圖中的模型及其關聯? –

回答

1

我相信,雖然我不確定,但您正在尋找訪問視圖中對象及其關聯的方式。那是對的嗎?

我會給你一個使用約會模型的例子。

AppointmentsController

class AppointmentsController < ApplicationController 
    def index 
    @appointments = Appointment.includes(:physician, :patient).order(:appointment_date) 
    end 
end 

約會#指數(Haml的語法)

%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 

這將使你與他們的日期,醫生和病人的任命名單。

這是您正在尋找的幫助嗎?

1

委任控制器:

def index 
    @appointments = Appointment.order("appointment_date DESC") 
end 

在約會#指數

<% for appointment in @appointments %> 

      <%= link_to appointment.patient.name, patients_path(appointment.patient) %> 
      &nbsp; 
      Appointment for 
      &nbsp; 
      <%= link_to appointment.physician.name, physician_path(appointment.physician) %> 
      <% if appointment.appointment_date? %> 

       <%= appointment.appointment_date %> 
      <% end %> 
    <% end %>