如何使用关联访问其他表的属性
“大家好”我现在正在使用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
谢谢你的时间!
也许我错过了一些东西,但是你忘了设置@appointment var吗?
def show
@appointment = Appointment.find(params['id'])
end
WHAAAAAAAAT ?!为什么!?!?!? omg我整天都在这里。如果该函数已经定义,我不明白它不应该被调用?我将这个定义定义为private,我认为那是从那里调用的。非常感谢你的帮助,我现在感觉非常愚蠢。 –
没有问题的朋友很高兴它解决了 –
您可以发布您的模型,以及(如果你有这样的路线应该工作)?我猜你错过了提及他们中的社团。 – Pramod
刚刚做到了!抱歉忘了添加它们。 Thx为您的时间! –