0

我正在使用http://guides.rubyonrails.org/来学习 ruby​​ 和 rails。我在加入三个表时遇到问题。,所以我做了一个新项目作为这个例子: http: //guides.rubyonrails.org/association_basics.html#the-has_many_through-association我有三个表医生,约会和病人

楷模:

医师.rb

class Physician < ActiveRecord::Base
    has_many :appointments
    has_many :patients, :through => :appointments
  attr_accessible :name
end

约会.rb

class Appointment < ActiveRecord::Base
    belongs_to :physician
    belongs_to :patient
  attr_accessible :appointment_date, :patient_id, :physician_id
end

病人.rb

class Patient < ActiveRecord::Base
    has_many :appointments
    has_many :physicians, :through => :appointments
  attr_accessible :name
end

我想显示患者姓名、医生姓名和约会日期。这个怎么做。提前致谢。

4

2 回答 2

1

尽管我不确定,但我相信您正在寻找访问视图中对象及其关联的方法。那是对的吗?

我会给你一个使用约会模型的例子。

约会控制器

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

这会给你一个约会列表,包括他们的日期、医生和病人。

这是您正在寻找的那种帮助吗?

于 2013-09-24T16:55:52.827 回答
1

预约控制器:

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

预约中#index

<% 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 %>
于 2013-10-31T11:45:48.113 回答