This is the situation in view components:
app/components/appointments/new_appointment_component.haml
= form_with(model: @appointment, url: appointments_path, method: :post) do |f|
= f.hidden_field :patient_id, value: @patient.id
%label= 'Doctor'
= f.collection_select(:doctor_id, @doctors, :id, :full_name)
%label= 'Date'
= f.datetime_select :appointment_date, start_year: Date.today.year, end_year: Date.today.year + 1, minute_step: 20
- if @appointment.errors[:appointment_date].any?
%p= @appointment.errors[:appointment_date].join(", ")
= f.submit 'Save'
= link_to "Back", patients_path
app/components/appointments/new_appointment_component.rb
# frozen_string_literal: true
class Appointments::NewAppointmentComponent < ViewComponent::Base
attr_reader :patient, :doctors, :appointment
def initialize(patient:, doctors:, appointment:)
@patient = patient
@doctors = doctors
@appointment = appointment
end
end
And I this controller and method create:
class AppointmentsController < ApplicationController
def index
render Appointments::AppointmentsComponent.new(appointments: Appointment.all)
end
def new
@patient = Patient.find(params[:patient_id])
render Appointments::NewAppointmentComponent.new(patient: @patient, doctors: Doctor.all, appointment: Appointment.new)
end
def create
@appointment = Appointment.new(appointment_params)
if @appointment.save
redirect_to root_path # root "patients#index"
#or render Appointments::AppointmentsComponent.new(appointments: Appointment.all)
else
render Appointments::NewAppointmentComponent.new(appointment: @appointment, patient: @appointment.patient, doctors: Doctor.all), content_type: "text/html"
end
end
private
def appointment_params
params.require(:appointment).permit(:patient_id, :doctor_id, :appointment_date, :price)
end
end
app/controllers/patients_controller.rb
and root
class PatientsController < ApplicationController
include Pagy::Backend
ITEMS_PER_PAGE = 10
def index
q = Patient.includes(:appointments).all.ransack(params[:q])
@pagy, @patients = pagy(q.result, items: ITEMS_PER_PAGE)
render Patients::PatientsComponent.new(patients: @patients, pagy: @pagy, q: q)
end
def show
@patient = Patient.find(params[:id])
render Patients::PatientDetailsComponent.new(patient: @patient)
end
end
and are problems in create method:
1.
when if @appointment.save
I want to redirect to some other page, but in DOM:
content from redirect_to root_path
is added below to body
, and I have content from existing component(app/components/appointments/new_appointment_component.haml
in body and below this contenct from root_path
. Why?
2)
when is else
refresh doesn't work and text from validation isn't visible.
What are the best solutions to solve it?
See the layout. It's located at
app/views/layouts/application.haml
if not custom. For debugging purposes, I would start by removing everything and just leaving= yield
along with the head (js/css files). If that helped, then read the code in the layout file carefully and fix it.