“大家好”我现在正在练习一下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“Template”时,即使它有一个值,也会给我一个错误,说明“Nil”中的医生参数。
<%= @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 :(得分:1)
也许我错过了一些东西,但是你没有忘记设置@appointment var?
def show
@appointment = Appointment.find(params['id'])
end
(如果你有这样的路线应该有用)