2
\$\begingroup\$

I have a Rails app where doctors score patients on diagnosis - their score is the model Baseline. Each Baseline has a user id and a patient id and there should only be one baseline for each patient by a user. Very occasionally I have noticed that a user may create a new baseline (at which point he is then redirected to another page) but then presses the back button, be brought to the "new" action again and if he submits again, a duplicate baseline is created. Therefore I am writing some code to try to ensure this never happens.

First, I check that a baseline doesn't already exist with the current user id and the patient id at the controller "new" action.

 before_action :check_there_is_not_an_existing_baseline, only: [:new ]

and

 def check_there_is_not_an_existing_baseline
 patient = Patient.find(params[:patient])
 @baseline = Baseline.where(user_id: current_user.id, patient_id: patient.id).first
 if @baseline
 flash[:notice] = "There was a problem with this action. Refresh the page and try again!"
 redirect_to list_patients_path(:page => @current_page)
 end
 end

I also check at the create action in the model

 validate :duplicate_baselines, :on => :create
 def duplicate_baselines
 check_baseline = Baseline.where(user_id: self.user_id, patient_id: self.patient_id)
 if !check_baseline.blank?
 errors.add(:base, "There was an error. Go to 'patient list' and start again") unless check_baseline.first.new_record?
 end
 end

I am trying to learn more and my suspicion is that there is good Rails way to do this. Could an expert have a look and see if there is a neater solution?

200_success
145k22 gold badges190 silver badges478 bronze badges
asked Jul 30, 2016 at 8:01
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

That can be done easily by Rails validation, and scope attribute:

# Baseline Model
validates :user_id, uniqueness: { scope: :patient_id }

That mean user_id can present many times in Baseline table, but only one can be connected to exact patient_id.

answered Jul 30, 2016 at 11:55
\$\endgroup\$
0

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.