我有 Rails 5 單體應用程式,在注冊表中,醫生/管理員可以創建一個注冊人(作為護理人員)和鏈接的患者(新物件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 驗證失敗:無法為看護者分配看護者
這是因為create!我猜但是如何處理這個以在表單中顯示 Flash 訊息?
uj5u.com熱心網友回復:
您可以使用事務: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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/446676.html
標籤:轨道上的红宝石
上一篇:如何在NEST查詢中使用條件Elasticsearch
下一篇:從陣列中回傳特定的字串格式
