vendredi 10 juin 2016

Copy rails active record object with it's associative records.(without using any gem)

I have a patient table which have following association.

has_one :patient_detail, dependent: :destroy
has_one :patient_diagnostic, dependent: :destroy
has_one :patient_therapy, dependent: :destroy 

I am copy the Patient object using this method. Is there any better way to perform this operation.?

def copy
    respond_to do |format|
      format.js{
        Patient.transaction do
          copied_patient = @patient.dup
          copied_patient.name += "(Copy)"
          begin
            if copied_patient.save
              copied_patient.patient_detail = @patient.patient_detail.dup
              copied_patient.patient_diagnostic = @patient.patient_diagnostic.dup
              copied_patient.patient_therapy = @patient.patient_therapy.dup
              if copied_patient.patient_detail.save && copied_patient.patient_diagnostic.save && copied_patient.patient_therapy       
                flash[:notice] = "Patients was copied successfully"
              else
                flash[:error] = copied_patient.errors.full_messages.join("<br>").html_safe
              end
            else
              flash[:error] = copied_patient.errors.full_messages.join("<br>").html_safe
            end
          rescue Exception => ex
            flash[:error] = ex.message
          end
        end
      }
      format.html{ redirect_to referral_ic_patients_path(current_ic) and return }
    end
  end

Aucun commentaire:

Enregistrer un commentaire