Rails has_many: через вложенную форму
Я только что вскочил в ассоциацию 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 %>
Я могу создать новую Patient
, Physician
и связанную запись для Appointment
, но теперь я хочу иметь поле для appointment_date
тоже в форме. Где я должен помещать поля для Appointment
и какие изменения требуются в моем контроллере? Я попробовал поиск по Google и попробовал этот, но застрял в той или иной ошибке, реализующей его.
Ответы
Ответ 1
Хорошо, этот маленький искатель вопроса захлестнул меня на несколько часов, поэтому я собираюсь опубликовать свое рабочее решение здесь, надеясь, что он починит некоторое время для подглядываний. Это для Rails 4.0 и Ruby 2.0. Это также преодолело проблему с символом "целочисленное преобразование".
Модель:
class Patient < ActiveRecord::Base
has_many :appointments
has_many :physicians, :through: :appointments
accepts_nested_attributes_for :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
accepts_nested_attributes_for :physician
end
class Physicians < ActiveRecord::Base
has_many :appointments
has_many :patients, through: :appointments
end
Контроллер:
def new
@patient= Patient.new
@appointments = @patient.appointments.build
@physician = @appointments.build_physician
end
def create
Patient.new(patient_params)
end
def patient_params
params.require(:patient).permit(:id, appointments_attributes: [:id, :appointment_time, physician_attributes: [:id ] )
end
Просмотр
<% 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 :appointments do |appointment_form| %>
<p>
<%= appointment_form.label :appointment_date, "Appointment Date" %>
<%= appointment_form.date_field :appointment_date %>
</p>
<% appointment_form.fields_for :physician do |physician_form| %>
<p>
<%= physician_form.label :name, "Physician Name" %>
<%= physician_form.text_field :name %>
</p>
<% end %>
<% end %>
<p>
<%= patient_form.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', patients_path %>
Ответ 2
"Я получил его работу. Я только что изменил модели следующим образом": цитируется из Shruti в комментариях выше
class Patient < ActiveRecord::Base
has_many :appointments, :dependent => :destroy
has_many :physicians, :through => :appointments
accepts_nested_attributes_for :appointments
end
class Appointment < ActiveRecord::Base
belongs_to :physician
belongs_to :patient
accepts_nested_attributes_for :physician
end
Ответ 3
Класс пациента принимает вложенные атрибуты как для врачей, так и для встреч. Попробуйте добавить еще один метод fields_for
для назначения.
<% 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 %>
<% patient_form.fields_for :appointments do |appointment_form| %>
<p>
<%= appointment_form.label :appointment_date, "Appointment Date" %>
<%= appointment_form.date_field :appointment_date %>
</p>
<% end %>
<p>
<%= patient_form.submit 'Create' %>
</p>
<% end %>
<%= link_to 'Back', patients_path %>