2013-09-23 56 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 %>