Appendix of the parent element at the stage of its establishment
-
Ruby On Rails started studying, and in the course of the example, he faced this issue. A slope description of the structure: there are doctors, there are patients, there are services. Service records should be maintained. So the session has a doctor, a patient, a favor. Created medical models, services, patient. There's a question about the seance model. Got these connections:
class Appointment < ActiveRecord::Base belongs_to :doctor belongs_to :patient belongs_to :service 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 class Service < ActiveRecord::Base has_many :appointments end
routes.rb
.. resources :patients do resources :appointments end resources :doctors do resources :appointments end resources :services do resources :appointments end resources :appointments ..
appointment_form.html.erb
<%= form_for @appointment do |f| %> <%= f.label :doctor, "Доктор:"%> <%= select(:doctor, :doctor_id, Doctor.all.collect {|p| [ p.lastname, p.id ] }) %> <%= f.label :patient, "Пациент:"%> <%= select(:patient, :patient_id, Patient.all.collect {|p| [ p.lastname, p.id ] }) %> <%= f.label :service, "Услуга:"%> <%= select(:service, :service_id, Service.all.collect {|p| [ p.name, p.id ] }) %> <%= f.label :date, "Дата оказания:" %><br> <%= f.date_select :date %> <%=f.submit ("Сохранить") %> <% end %>
appointments_controller.rb
class AppointmentsController < ApplicationController def new @appointment = Appointment.new end def create @patient = Patient.find(params[:patient][:patient_id]) @doctor = Doctor.find(params[:doctor][:doctor_id]) @service = Service.find(params[:service][:service_id]) @appointment = @patient.appointments.new(appointment_params) if @appointment.save redirect_to @appointment else render 'new' end end private def appointment_params params.require(:appointment).permit(:date) end end
Question: How do I add a session? Now, I'm in the patient's control room first, and I'm already adding a session, and in the end, only the fields of the patient and the day are filled in. How do you transfer the remaining fields (a doctor, a favor)?
-
In method
create
The addition of a doctor and a new session should be implemented:def create @patient = Patient.find(params[:patient][:patient_id]) @doctor = Doctor.find(params[:doctor][:doctor_id]) @service = Service.find(params[:service][:service_id]) @appointment = @patient.appointments.new(appointment_params)
if @appointment.save success = false #+++ @doctor.appointments << @appointment #+++ if @doctor.save then success = true #+++ @service.appointments << @appointment #+++ if @service.save and success then #+++ redirect_to @appointment else #+++ render 'new' #+++ end #+++ else render 'new' end
end