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 ]


 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)

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?

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?


1 Answer 1


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.


Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.