「みなさんこんにちは」私は今、レールで少し練習していますが、アソシエーションを使ってデータにアクセスする方法を理解しています。現在私は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 %>
データが挿入されているが、私はショー「テンプレート」を呼び出したときに私に言って、エラーを与えていること、それは価値があるにもかかわらず、「無記号」の医師のためのパラメータ。
<%= @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
ありがとうございました!
あなたにも、あなたのモデルを投稿することができます?。私はあなたが彼らの中の団体に言及するのを忘れていたと思います。 – Pramod
ちょうどした!申し訳ありません、それらを追加するのを忘れました。あなたの時間のためのThx! –