Ruby on rails 如何仅编辑和销毁我自己的内容?

Ruby on rails 如何仅编辑和销毁我自己的内容?,ruby-on-rails,devise,Ruby On Rails,Devise,有一个基本的博客(实际上是edgeguide的博客:) 然后我把这个设计融入其中。所以,用户只能登录并查看自己的信息 现在,我正试图改变它 我希望用户看到所有内容,但只编辑和销毁自己的内容 尝试在执行操作之前使用过滤器,如下所示: `before_action :authorize, :only => [:edit, :destroy]` 这是我写的授权方法: def authorize @article = Article.find(params[:id])

有一个基本的博客(实际上是edgeguide的博客:)

然后我把这个设计融入其中。所以,用户只能登录并查看自己的信息

现在,我正试图改变它

我希望用户看到所有内容,但只编辑和销毁自己的内容

尝试在执行操作之前使用
过滤器,如下所示:

 `before_action :authorize, :only => [:edit, :destroy]`
这是我写的授权方法:

     def authorize
       @article = Article.find(params[:id])
        if !@article.user_id = current_user.id then 
        flash[:notice] = "You are not the creator of this article, therefore you're not permitted to edit or destroy this article"
    end
end
但它不起作用。一切正常,我可以删除我和其他人的内容

我如何才能做到只销毁自己的内容,而不销毁其他人的内容

不使用CanCan,我也不想

不确定这是否值得包括在内,但最初我让每个人都看到自己的内容时,是通过创建操作:

   def create
    @article = Article.new(article_params)
    @article.user_id = current_user.id if current_user
    if @article.save

        redirect_to @article
    else
        render 'new'
    end
end

你有几个问题

首先,请看:

if !@article.user_id = current_user.id then 
您只使用了一个
=
而不是
=
,因此您正在执行一个赋值,该赋值将计算为
当前用户id

此外,在您的情况下,您只是设置了一条flash消息,而没有采取任何措施来真正阻止用户

下面是一个更正的版本:

def authorize
  @article = Article.find(params[:id])
  unless @article.user_id == current_user.id 
    flash[:notice] = "You are not the creator of this article, therefore you're not permitted to edit or destroy this article"
    redirect_to root_path # or anything you prefer
    return false # Important to let rails know that the controller should not be executed
  end
end
谢谢(此处作为注释的附加绒毛字符长度要求为15个字符,哈!)