RAILS: preventing the duplicate submission of an object.

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?

Thank you

Replay

Category: ruby on rails Time: 2016-07-30 Views: 0

Related post

iOS development

Android development

Python development

JAVA development

Development language

PHP development

Ruby development

search

Front-end development

Database

development tools

Open Platform

Javascript development

.NET development

cloud computing

server

Copyright (C) avrocks.com, All Rights Reserved.

processed in 0.141 (s). 12 q(s)