Skip to content

Instantly share code, notes, and snippets.

@forksofpower
Created April 9, 2020 15:45
Show Gist options
  • Save forksofpower/6d8db3a7f4e2c79a11b46b2ec872f9c4 to your computer and use it in GitHub Desktop.
Save forksofpower/6d8db3a7f4e2c79a11b46b2ec872f9c4 to your computer and use it in GitHub Desktop.
Rails Controller Example with Error Messages
class StudentsController < ApplicationController
before_action :find_student, except: [:index, :new, :create]
def index
@students = Student.all
end
def show
end
def new
@student = Student.new
end
def edit
end
def create
@student = Student.new(params[:student])
if @student.save
flash[:success] = "Student successfully created"
redirect_to @student
else
flash[:error] = "Something went wrong"
render 'new'
end
end
def update
if @student.update_attributes(params[:student])
flash[:success] = "Student was successfully updated"
redirect_to @student
else
flash[:error] = "Something went wrong"
render 'edit'
end
end
def destroy
if @student.destroy
flash[:success] = "Student was successfully deleted"
redirect_to @students_path
else
flash[:error] = "Something went wrong"
redirect_to @students_path
end
end
private
def find_student
@student = Student.find(params[:id])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment