在rails 4

时间:2016-06-14 20:14:56

标签: ruby-on-rails ruby database activerecord

我目前正致力于"练习"在许多关系中使用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

是的,我没有很多代码。我不是在使用脚手架而是自己建造一切。 (这是我觉得我学得最好的方式。)我得到的具体错误如下:未定义的方法physicians' for #<Appointment:0x007fa7d5bf7370> as well as undefined method每个&#39;对于#如果我改变拿走以下行中的s - 因为它与控制器中的医生变量不匹配:

&lt;%appointment.physician.each do | physician | %GT; (这显示了我可以轻松解决的每条错误消息。)

现在,我正在学习如何使用多个数据库。我可以让医生ID显示没问题。但是,我想进入医生数据库并根据医生ID提取名称。 (希望这是有道理的。)任何帮助将不胜感激!谢谢你的帮助!

1 个答案:

答案 0 :(得分:0)

由于PhysicianPatient belong_to Appointment,它是一对多关联。因此,您需要将关联称为单数:

appointment.physician # not physicians
appointment.patient # not patients

您的观点应如下所示:

<h1>Showing Appointments</h1>
<% @appointments.each do |appointment| %>
    <h3><%= appointment.physician.name %></h3>
<% end %>

所有这一切,似乎你的协会都没有了。 belongs_to关联意味着关联模型只能属于一个模型。这意味着,您当前的设置意味着PhysicianPatient只能属于一个Appointment,这几乎肯定不是这种情况。在这种情况下,我认为has_one似乎更合适:

class Appointment < ActiveRecord::Base
  has_one :physician 
  has_one :patient
end

其余的保持不变!