I am creating a site similar to Reddit. I would like the moderator to be able to update the topic, but could not create or delete the topic. I know that I need to update ThemeController, but I'm not sure how to do it. My main problem is that I'm not sure how to make the code specific enough to make sure that the moderator can only update; Do not delete or create a theme as the administrator can.
My current code is as follows:
class PostsController < ApplicationController
before_action :require_sign_in, except: :show
before_action :authorize_user, except: [:show, :new, :create]
def show
@post = Post.find(params[:id])
end
def new
@topic = Topic.find(params[:topic_id])
@post = Post.new
end
def create
@post.body = params[:post][:body]
@topic = Topic.find(params[:topic_id])
@post = @topic.posts.build(post_params)
@post.user= current_user
if @post.save
flash[:notice] = "Post was saved"
redirect_to [@topic, @post]
else
flash[:error] = "There was an error saving the post. Please try again."
render :new
end
end
def edit
@post = Post.find(params[:id])
end
def update
@post = Post.find(params[:id])
@post.assign_attributes(post_params)
if @post.save
flash[:notice] = "Post was updated."
redirect_to [@post.topic, @post]
else
flash[:error] = "There was an error saving the post. Please try again."
render :edit
end
end
def destroy
@post = Post.find(params[:id])
if @post.destroy
flash[:notice] = "\"#{@post.title}\" was deleted successfully."
redirect_to @post.topic
else
flash[:error] = "There was an error deleting the post."
render :show
end
end
private
def post_params
params.require(:post).permit(:title, :body)
end
def authorize_user
post = Post.find(params[:id])
unless current_user == post.user || current_user.admin?
flash[:error] = "You must be an admin to do that."
redirect_to [post.topic, post]
end
end
end
I have already added the moderator role of the enum role.
I apologize if this seems really basic ... but it puzzled me!
Thanks in advance!
source
share