【问题标题】:Joining Three tables in Rails3在 Rails3 中连接三个表
【发布时间】:2013-09-28 14:33:08
【问题描述】:

我正在使用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

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

【问题讨论】:

  • 你有为这些模型构建的控制器和视图吗?
  • 是的,我有所有三个模型的控制器和视图。
  • 那么,您是否只是想知道如何在视图中访问模型及其关联?

标签: ruby-on-rails-3 associations has-many-through


【解决方案1】:

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

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

AppointmentsController

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

appointments#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

这将为您提供一个约会列表,其中包含约会日期、医生和患者。

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

【讨论】:

    【解决方案2】:

    预约控制器:

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

    【讨论】:

      猜你喜欢
      • 2016-12-07
      • 2012-02-06
      • 1970-01-01
      • 1970-01-01
      • 2016-12-20
      • 2018-11-06
      • 2014-02-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多