Created
October 8, 2016 23:15
-
-
Save beaugaines/e4d586525c5e11319a09ef17e21594d5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class TopicsController < ApplicationController | |
before_action :require_sign_in, except: [:index, :show] | |
before_action :authorize!, except: [:index, :show] | |
def index | |
@topics = Topic.all | |
end | |
def new | |
@topic = Topic.new | |
end | |
def create | |
@topic = Topic.new(topic_params) | |
if @topic.save | |
flash[:notice] = "Topic was saved successfully." | |
redirect_to @topic | |
else | |
flash.now[:alert] = "Error creating topic. Please try again." | |
render :new | |
end | |
end | |
def show | |
@topic = Topic.find(params[:id]) | |
end | |
def update | |
@topic = Topic.find(params[:id]) | |
@topic.assign_attributes(topic_params) | |
if @topic.save | |
flash[:notice] = "Topic was updated successfully." | |
redirect_to @topic | |
else | |
flash.now[:alert] = "Error saving topic. Please try again." | |
render :edit | |
end | |
end | |
def edit | |
@topic = Topic.find(params[:id]) | |
end | |
def destroy | |
@topic = Topic.find(params[:id]) | |
if @topic.destroy | |
flash[:notice] = "\"#{@topic.name}\" was deleted successfully." | |
redirect_to action: :index | |
else | |
flash.now[:alert] = "There was an error deleting the topic." | |
render :show | |
end | |
end | |
private | |
def topic_params | |
params.require(:topic).permit(:name, :description, :public) | |
end | |
def authorize! | |
case action_name | |
when :edit, :update | |
unless current_user.admin? || current_user.moderator? | |
redirect_to topics_path, alert: 'You are not authorized to do that' | |
end | |
when :new, :create, :destroy | |
unless current_user.admin? | |
redirect_to topics_path, alert: 'You are not authorized to do that' | |
end | |
end | |
end | |
k | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment