我刚刚开始了解has_many :through
关联。我正在尝试通过单个表格实现保存所有三个表格(Physician
、Patient
和关联表)的数据的能力。
我的迁移:
class CreatePhysicians < ActiveRecord::Migration
def self.up
create_table :physicians do |t|
t.string :name
t.timestamps
end
end
end
class CreatePatients < ActiveRecord::Migration
def self.up
create_table :patients do |t|
t.string :name
t.timestamps
end
end
end
class CreateAppointments < ActiveRecord::Migration
def self.up
create_table :appointments do |t|
t.integer :physician_id
t.integer :patient_id
t.date :appointment_date
t.timestamps
end
end
end
我的模型:
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through => :appointments
accepts_nested_attributes_for :appointments
accepts_nested_attributes_for :physicians
end
class Physician < ActiveRecord::Base
has_many :appointments
has_many :patients, :through => :appointments
accepts_nested_attributes_for :patients
accepts_nested_attributes_for :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
end
我的控制器:
def new
@patient = Patient.new
@patient.physicians.build
@patient.appointments.build
end
我的视图 (new.html.rb
):
<% form_for(@patient) do |patient_form| %>
<%= patient_form.error_messages %>
<p>
<%= patient_form.label :name, "Patient Name" %>
<%= patient_form.text_field :name %>
</p>
<% patient_form.fields_for :physicians do |physician_form| %>
<p>
<%= physician_form.label :name, "Physician Name" %>
<%= physician_form.text_field :name %>
</p>
<% end %>
<p>
<%= patient_form.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', patients_path %>
我能创建一个新的患者,医生和关联记录以进行约会,但现在我想在表单中加入预约日期字段。我应该在哪里放置预约的字段,并且我的控制器需要做出什么改变?我尝试了谷歌和尝试这个,但在实施过程中卡住了。
t.references: patient
,而不是t.integer: patient_id
来创建适当类型的列。请参阅http://guides.rubyonrails.org/migrations.html#special-helpers。 - Robin