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

时间:2014-03-16 21:49:13

标签: ruby-on-rails devise

拥有一个基本博客(实际上是edgeguide的博客:http://edgeguides.rubyonrails.org/getting_started.html

然后我将Devise集成到其中。因此,用户只能登录并查看自己的信息。

现在尝试改变它。

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

尝试使用before_action过滤器,如下所示:

 `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

1 个答案:

答案 0 :(得分:2)

你有几个问题

首先,看看:

if !@article.user_id = current_user.id then 

您只使用一个=代替==,因此您正在进行评估为current_user.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
相关问题