加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 更新TopicsController以允许主持人更新主题,但

发布时间:2020-12-17 01:55:49 所属栏目:百科 来源:网络整理
导读:我正在创建一个类似于Reddit的网站.我想允许主持人能够更新主题,但无法创建或删除主题.我知道我需要更新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授权.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读