检查current_user是帖子的作者

时间:2013-11-29 21:55:06

标签: ruby-on-rails ruby-on-rails-4

我正在尝试将编辑功能限制在我的rails应用程序中的文章作者。

在我的控制器中,我正在添加用户ID作为工作正常:

def create
  @article = Article.new(article_params)
  @article.author = current_user.id
  ...
 end

然后在编辑操作上检查它:

def edit
  @article = Article.find(params[:id])
  redirect_to root_path, notice: 'Whoa there amigo!' unless current_user.id == @article.author
end

每次都重定向编辑结果。

(我现在不使用Devise,CanCan或其他任何东西,因为这是我现在唯一需要的功能。)

更新

根据评论,我将我的创建方法更新为:

def create
  @article = current_user.articles.build(article_params)

和我的编辑方法:

def edit
  @article = current_user.articles.find(params[:id])
  redirect_to root_path, notice: 'Whoa..' unless current_user.id.to_s == @article.user_id

这样可行,但“current_user.id.to_s”对于一些必须非常普遍的事情似乎有些苛刻。

1 个答案:

答案 0 :(得分:0)

在创建动作中:

def create
  @article = Article.new(article_params)
  @article.author = current_user
  ...
end

在编辑中将条件更改为:

unless current_user == @article.author

这样您可以比较用户对象而不是用户ID对象。