2013-09-23 5 views
0

ruby ​​& 레일을 배우려면 http://guides.rubyonrails.org/을 사용하고 있습니다. 3 개의 테이블을 조인하는 데 문제가 있습니다. 그래서이 예제로 새로운 프로젝트를 만들어 : 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

예 컨트롤러와 3 가지 모델 모두에 대한 뷰가 있습니다. –

+0

그럼,보기에서 모델과 연관을 액세스하는 방법에 대해 궁금한 점이 있습니까? –

답변

1

나는 확신 할 수는 없겠지만, 당신이보기에서 객체와 그들의 연관에 액세스하는 방법을 찾고 있다고 생각합니다. 그 맞습니까?

약속 모델을 사용하여 예제를 제공합니다.

AppointmentsController

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

약속 # 지수 이것은 당신에게 그들의 날짜, 의사, 환자와 약속의 목록을 줄 것이다

%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 

(HAML 구문).

당신이 찾고있는 일종의 도움인가요? 약속 컨트롤러에서

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 %>