ruby-on-rails – 更新TopicsController以允许主持人更新主题,但不能创建或删除

我正在创建一个类似于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

我已经为枚举角色添加一个主持人角色.

如果这看起来非常基本,我道歉…但它让我难过!

提前致谢!

解决方法

我可以回答一些自定义解决方案,但最好使用更结构化和社区审核的方法:使用 cancan授权.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...