2017-01-01 92 views
0

「大家好」我現在正在使用rails練習一點點,並且遇到關於如何通過關聯訪問數據的問題。目前我有3張桌子,醫生,病人和約會。如何使用關聯訪問其他表的屬性

 class CreateDoctors < ActiveRecord::Migration 
     def change 
     create_table :doctors do |t| 
      t.string :name 

      t.timestamps null: false 
     end 
     end 
    end 

     class CreatePatients < ActiveRecord::Migration 
     def change 
     create_table :patients do |t| 
      t.string :name 

      t.timestamps null: false 
     end 
     end 
    end 

     class CreateAppointments < ActiveRecord::Migration 
     def change 
     create_table :appointments do |t| 
      t.date :date_appointment 
      t.references :doctor, index: true, foreign_key: true 
      t.references :patient, index: true, foreign_key: true 

      t.timestamps null: false 
     end 
     end 
    end 

有了這個,我想創建一個表單上插入約會表記錄,這樣我可以訪問並提交表單後得到任何醫生或病人的姓名。

<%= form_for(@appointment) do |f| %> 
<%= f.label :date, "Choose a date for your appointment" %> 
<%= f.collection_select(:doctor_id, Doctor.all, :id, :name, prompt: true) %> 
<%= f.submit %> 
<% end %> 

的數據被插入,但是當我調用Show「模板」是給我的錯誤,指出該參數醫生「零」,即使它有一個值。

<%= @appointment.doctor.name %> 

而這裏的任命控制器數據

 class AppointmentsController < ApplicationController 

     def index 
     end 

     def show 

     end 

     def new 
      @appointment = Appointment.new 
     end 

     def create 
      @appointment = Appointment.new(appointment_params) 
      if @appointment.save 
       redirect_to @appointment 
      else 
       render "New" 
      end 
     end 

     private 

     def appointment_params 
      params.require(:appointment).permit(:date, :doctor_id, :patient_id) 
     end 

     def find_appointment 
      @appointment = Appointment.find(params[:id]) 
     end 



     end 

我想要做的是基本能夠根據該行的屬性值來呈現或顯示醫生,患者的姓名是正在使用表單創建新行後創建。

class Appointment < ActiveRecord::Base 
     belongs_to :doctor 
     belongs_to :patient 
    end 

class Doctor < ActiveRecord::Base 
    has_many :appointments 
    has_many :patients, through: :appointments 
end 

class Patient < ActiveRecord::Base 
    has_many :appointments 
    has_many :doctors, through: :appointments 
end 

謝謝你的時間!

+0

您可以發佈您的模型,以及(如果你有這樣的路線應該工作)?我猜你錯過了提及他們中的社團。 – Pramod

+0

剛剛做到了!抱歉忘了添加它們。 Thx爲您的時間! –

回答

1

也許我錯過了一些東西,但是你忘了設置@appointment var嗎?

def show 
    @appointment = Appointment.find(params['id']) 
end 

+0

WHAAAAAAAAT ?!爲什麼!?!?!? omg我整天都在這裏。如果該函數已經定義,我不明白它不應該被調用?我將這個定義定義爲private,我認爲那是從那裏調用的。非常感謝你的幫助,我現在感覺非常愚蠢。 –

+0

沒有問題的朋友很高興它解決了 –

相關問題