I used this page to help me validate if adding a new entry (add a new exercise in my case) which worked great Check if record exists from controller in Rails
But I can't quite seem to get it to work if I'm updating/editing an exercise.
In plain English I'm trying to:
Get current exercise record the user wants to edit(done), user updates the values(done), submits(done), the controller checks the user's input against the db to see if a record already exists with the same name, if it exists error, if not, update.
Thanks.
Here's the part of my controller that I can't quite get going for update:
class ExercisesController < ApplicationController
before_action :authenticate_user!, :except => [:index, :show]
before_filter :set_exercise, only: [:show, :edit, :update, :destroy, :upvote, :downvote]
def new
@exercise = Exercise.new
end
def create
@exercise = current_user.exercises.build(exercise_params)
if Exercise.exists?(name: @exercise.name)
flash.now[:danger] = "Exercise has not been created, duplicate entry"
render :new
elsif @exercise.save
flash[:success] = "Exercise has been created"
redirect_to exercises_path
else
flash.now[:danger] = "Exercise has not been created"
render :new
end
end
def edit
if !current_user.admin?
flash[:danger] = "You are not an admin"
redirect_to root_path
end
end
def update
if !current_user.admin?
flash[:danger] = "You are not an admin"
redirect_to root_path
else
if Exercise.where(:name => @exercise.name).any?
flash.now[:danger] = "Exercise has not been updated, duplicate entry"
render :edit
elsif @exercise.update(exercise_params)
flash[:success] = "Exercise has been updated"
redirect_to @exercise
else
flash.now[:danger] = "Exercise has not been updated"
render :edit
end
end
end
private
def exercise_params
params.require(:exercise).permit(:name, :description, :summary)
end
def set_exercise
@exercise=Exercise.find(params[:id])
end