我正在创建一个类似于Reddit的网站.我想允许主持人能够更新主题,但无法创建或删除主题.我知道我需要更新TopicsController,但我不确定如何.我的主要问题是我不确定如何使代码具体到足以确保主持人只能更新;不能像管理员那样删除或创建主题.
我当前的代码如下所示:
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
如果这看起来非常基本,我道歉…但它让我难过!
提前致谢!
解决方法
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。