我刚刚加入has_many :through
协会。我正在尝试通过一个表单实现为所有 3 个表(和关联表)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 %>
我可以为 an 创建一个新Patient
的Physician
和关联的记录Appointment
,但现在我想appointment_date
在表单中也有字段。我应该在哪里放置Appointment
s 的字段以及在我的控制器中需要进行哪些更改?我尝试了谷歌搜索并尝试了这个,但在实现它时遇到了一些或其他错误。