我有一个叫的模型Article
。
在我的中ArticlesController
,我设置了文章操作,以设置您必须以用户身份登录的位置,然后才能执行除我index
和show
操作之外的任何操作。
这是我的articles_controller.rb
:
class ArticlesController < ApplicationController
http_basic_authenticate_with name: "dhh", password: "secret", except: [:index, :show]
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
def update
@article = Article.find(params[:id])
if @article.update(article_params)
redirect_to @article
else
render 'edit'
end
end
def destroy
@article = Article.find(params[:id])
@article.destroy
redirect_to articles_path
end
private
def article_params
(params.require(:article).permit(:title, :text))
end
end
如何设置的Article
行动,以便只有在管理员可以做基本的CRUD功能上(创建/读取/更新/删除)Article
?
是否可以使用Admin
模型制作模型Devise
(我目前没有管理员模型)?
Devise
控制器中是否具有供管理员使用的功能或方法?
无论您使用的是gem还是滚动自己的授权,我都可以通过创建一个额外的控制器来解决。对于普通用户:
class ArticlesController < ApplicationController
before_action :some_basic_authorization
def index
@articles = Article.all
end
def show
@article = Article.find(params[:id])
end
...
end
您的管理员用户可能会执行比对文章执行CRUD操作更多的操作,因此建议您不要执行每个控制器中的重复授权,而是建议执行以下操作:
class AdminsController < ApplicationController
some_admin_authorization
end
然后,您将创建专用的管理控制器并从该授权类继承。在您的情况下,这可能看起来像:
class AdminArticlesController < AdminsController
def new
@article = Article.new
end
def edit
@article = Article.find(params[:id])
end
...
end
只有管理员才能访问这些控制器中指定的操作。附带的好处是,您可以创建自定义的显示视图和索引视图,这些视图对管理员来说是专门的并且更有用。例如,它们将包括普通用户不需要的大型编辑和删除按钮。这也使授权逻辑和if / else语句不在您的视图之内。
我认为,在一个地方使用单独的控制器并授权管理员,可以使代码更具可读性,并且可以很好地分离关注点。在此处详细了解此内容:http : //guides.rubyonrails.org/action_controller_overview.html#http-basic-authentication
您可以通过使用管理名称空间来进一步迈出这一步,您可以在此处阅读以下内容:http : //guides.rubyonrails.org/routing.html#controller-namespaces-and-routing
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句