如果您只想拥有 1 个用户,一个管理员,具有登录名和密码,并且没有其他用户帐户,那么我会推荐 HTTP Digest Auth,它由 rails 开箱即用支持并且不不需要任何额外的宝石或插件。 (或 HTTP 基本身份验证,但摘要式身份验证更安全。)
以下大部分内容来自 rails 网站上的action controller guide。
在 config/routes.rb 中:
resources :posts
在控制器/posts_controller.rb 中:
class PostsController < ActionController::Base
USERS = { "admin" => "password" }
before_action :authenticate, except: [:index, :show]
# actions here (index, show, new, create, edit, update, destroy)
private
def authenticate
authenticate_or_request_with_http_digest do |username|
USERS[username]
end
end
end
如果需要,您可以修改路由,以便新/创建/编辑/更新/销毁操作位于网站的“管理/”部分:
在 config/routes.rb 中:
scope '/admin' do
resources :posts, except: [:index, :show]
end
resources :posts, only: [:index, :show]
这仍会将所有与帖子相关的请求定向到 PostsController。