Home > Software design >  How to use before_save (with params) to check if a record exist
How to use before_save (with params) to check if a record exist

Time:04-13

I would like to check if a record exist before_save, what's the best way tod do that ?

def create
  @step = Step.new(step_params)
  @course = Course.find(step_params[:course_id])
  redirect_to course_path(@course) and return if step_already_present?(@step)

  if @step.save
    redirect_to course_path(@course.id)
  else
    render :new
  end
end

The method to check :

def step_already_present?(step)
  Step.where(poi_start_id: step.poi_start_id, course_id: step.course_id).first.present?
end

CodePudding user response:

You can use the uniqueness validation on the Model

If you need to check the two columns together you can use the scope option like this:

class Step < ActiveRecord::Base
  validates :poi_start_id, uniqueness: { scope: :course_id }
end
  • Related