Rails 从子模型渲染 Flash 错误信息

Rails render flash error message from child model

我有 Rails 5 monolith 应用程序,其中在注册表单中 Doctor/Admin 可以创建一个注册人(作为护理人员)与链接的患者(新对象 CaregiverPatient 表示) .

  def create
    @registrant = Registrant.new(registrant_params)
    @patient = Registrant.find(session[:patient_id_to_add_caregiver]) if session[:patient_id_to_add_caregiver]
    if @registrant.save
      # other objects that must be created (...)
      CaregiverPatient.create!(patient: @patient, caregiver: @registrant, linked_by: current_login.user.id, link_description: 0) if @patient.present?
      redirect_to registrant_path(@registrant), notice: 'Registrant Added'
    else
      build_registrant_associations
      render :new, { errors: errors.full_message }
    end
  end

看护人只能有一个关联的患者。如果发生此类错误,如何显示 CaregiverPatient 验证的错误消息并防止保存 @registrant

使用此代码时出现错误:

ActiveRecord::RecordInvalid in RegistrantsController#create Validation failed: Caregiver cannot be assigned a caregiver

我猜是因为 create! 但如何处理这个以在表单内显示 flash 消息?

您可以使用交易:https://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html

这允许您处理来自 create!save! 的异常并防止 @registrant 被保存。

我认为您的代码应该类似于

def create
  @registrant = Registrant.new(registrant_params)
  @patient = Registrant.find(session[:patient_id_to_add_caregiver]) if session[:patient_id_to_add_caregiver]

  begin
      ActiveRecord::Base.transaction do
          @registrant.save!
          #other objects creation
          CaregiverPatient.create!(patient: @patient, caregiver: @registrant, linked_by: current_login.user.id, link_description: 0) if @patient.present?
          redirect_to registrant_path(@registrant), notice: 'Registrant Added'
      end
  rescue ActiveRecord::RecordInvalid => exception
      build_registrant_associations
      render :new, { errors: exception.message }
  end
end