我最近完成了 http://guides.rubyonrails.org/getting_started.html 并添加了用户身份验证系统,因此只有注册用户才能创建/删除博客文章/文章。 但是,目前任何用户都可以删除任何文章。 我想将对文章的删除/销毁操作的访问权限限制为文章的所有者,即只有文章的所有者才能删除它。
更新我的代码文件如下所示,
Articles_controller.rb
class ArticlesController < ApplicationController
def destroy
@article = Article.find_by_slug(params[:id])
if current_user == @article.user
@article.destroy
end
redirect_to articles_path
end
文章.rb
class Article < ActiveRecord::Base
# user singluar form of model when using 'belongs_to'
# see this SO thread, http://stackoverflow.com/questions/16257116
belongs_to :user
用户.rb
class User < ActiveRecord::Base
has_many :articles
和迁移文件 AddUserIdToArticles.rb
class AddUserIdToArticles < ActiveRecord::Migration
def change
add_column :articles, :user_id, :integer
add_column :users, :user_id, :integer
add_foreign_key :articles, :users
end
end
假设你有一个辅助函数current_user
,你可以在文章中执行以下操作控制器:
def destroy
@article=Article.find(params[:id])
if current_user == @article.user
@article.destroy
end
redirect_to root_path
end
现在,仅当登录current_user
是帖子的实际作者时,才会执行销毁操作
我会使用诸如cancancan或pundit之类的授权宝石;这些允许您像描述的那样显式设置授权。对于非常简单的情况,也可以只编写自己的内容,例如
private
def set_article
@article = current_user.articles
end
然后设置创建之前筛选器before_filter :set_article, only: [:index, :show]
唯一的部分是可选的,可以省略,以便筛选器应用于控制器中的所有方法。
# user model
has_many :articles
# controller
def destroy
current_user.articles.find(params[id]).destroy
redirect_to root_path
end
如果current_user不是文章的所有者,代码也会引发 404