rails 中的 view_componets 渲染问题

问题描述 投票:0回答:1

这是视图组件中的情况:

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

我创建了这个控制器和方法:

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
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

并且是创建方法中的问题:

1. 当

if @appointment.save
我想重定向到其他页面,但在 DOM 中时: 来自
redirect_to root_path
的内容添加到了下面的
body
中,并且我有来自现有组件(正文中的
app/components/appointments/new_appointment_component.haml
以及来自
root_path
的内容下方的内容。为什么?

2) 什么时候

else
刷新不起作用,验证文本不可见。

解决这个问题的最佳解决方案是什么?

ruby-on-rails rendering view-components
1个回答
0
投票

查看布局。如果不是自定义的话,它位于

app/views/layouts/application.haml
。出于调试目的,我首先删除所有内容,只留下
= yield
和头部(js/css 文件)。如果有帮助,请仔细阅读布局文件中的代码并修复它。

© www.soinside.com 2019 - 2024. All rights reserved.