【发布时间】:2016-06-14 20:14:55
【问题描述】:
我目前正在使用 Rails 4 进行多对多关系的“实践”项目。这确实是我真正不知道如何处理 Rails 的少数几件事之一。目前,我有两个模型——一个医生模型和一个病人模型。我已经将它们与约会模型联系在一起。这是我到目前为止的代码:(我将只包括医生和任命代码,因为我目前没有使用患者模型。)
医师型号代码:
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, :through => :appointments
end
约会模型代码:
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end
医师控制者:
class PhysiciansController < ApplicationController
def index
@physicians = Physician.all
end
end
约会控制器:
class AppointmentsController < ApplicationController
def index
@appointments = Appointment.all
@physicians = Physician.all
end
end
约会索引页面代码-我想在其中显示每次约会的医生:
<h1>Showing Appointments</h1>
<% @appointments.each do |appointment| %>
<% appointment.physicians.each do |physician| %>
<h3><%= appointment.physicians.name %></h3>
<% end %>
<% end %>
架构:
create_table "appointments", force: :cascade do |t|
t.integer "physician_id"
t.integer "patient_id"
t.datetime "appointment_date"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "patients", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "physicians", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
如果需要我的路线:
resources :patients
resources :physicians
resources :appointments
是的,我没有很多代码。我没有使用脚手架并自己建造所有东西。 (这是我觉得我学得最好的方式。)我得到的具体错误如下: undefined method physicians' for #<Appointment:0x007fa7d5bf7370> as well as undefined methodeach' for # if I change take away the s in the following line-因为它不匹配控制器中的医生变量:
(这显示了我可以轻松解决的每条错误消息。)
现在,我再次学习如何使用多个数据库。我可以让医生 id 看起来没有问题。但是,我想进入医生数据库并根据医生 ID 提取名称。 (希望这是有道理的。)任何帮助将不胜感激!感谢您的帮助!
【问题讨论】:
标签: ruby-on-rails ruby database activerecord