我正在使用http://guides.rubyonrails.org/来学习ruby&轨道。加入三个表我有问题。 ,所以我做了一个新项目作为这个例子:http://guides.rubyonrails.org/association_basics.html#the-has_many_through-association我有三个表医生,约会&患者
型号:
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
我想显示患者姓名,医生姓名和姓名。约会日期。这该怎么做。 提前谢谢。
答案 0 :(得分:1)
我相信,虽然我不确定,但您正在寻找在视图中访问对象及其关联的方法。那是对的吗?
我将使用约会模型给你一个例子。
AppointmentsController
class AppointmentsController < ApplicationController
def index
@appointments = Appointment.includes(:physician, :patient).order(:appointment_date)
end
end
约会#index(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 :(得分:1)
在预约控制器中:
def index
@appointments = Appointment.order("appointment_date DESC")
end
在约会#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 %>