运维开发网

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

运维开发网 https://www.qedev.com 2020-07-23 21:51 出处:网络 作者:运维开发网整理
我正在创建一个类似于Reddit的网站.我想允许主持人能够更新主题,但无法创建或删除主题.我知道我需要更新TopicsController,但我不确定如何.我的主要问题是我不确定如何使代码具体到足以确保主持人只能更新;不能像管理员那样删除或创建主题. 我当前的代码如下所示: class PostsController < ApplicationController before_action
我正在创建一个类似于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授权.
0

精彩评论

暂无评论...
验证码 换一张
取 消