Rails,Devise:相同的资源,基于用户类型的不同的控制器 [英] Rails, Devise: Same resource, different controller based on user type
问题描述
我有一个资源,说产品
,可以由两个不同的用户类访问:说客户
和管理
。这两个之间没有遗产。
I have a resource, say Product
, which can be accessed by two different user classes: say Customer
and Admin
. There is no inheritance between these two.
我正在使用Devise进行身份验证:
I am using Devise for authentication:
# config/routes.rb
devises_for :customers
deviser_for :admins
我有这两个控制器:
# app/controllers/customers/products_controller.rb
class Customers::ProductsController < ApplicationController
和
# app/controllers/admins/products_controller.rb
class Admins::ProductsController < ApplicationController
现在取决于谁登录(客户
或 Admin
),我想要 products_path
指向相应的控制器。而且我想避免使用 customers_products_path
和 admins_products_path
,这很麻烦。
Now depending on who logs in (Customer
or Admin
), I want products_path
to point to the corresponding controller. And I want to avoid having customers_products_path
and admins_products_path
, that's messy.
所以我设置了我的路线这样
So I have setup my routes as such
# config/routes.rb
devise_scope :admin do
resources :products, module: 'admins'
end
devise_scope :customer do
resources :products, module: 'customers'
end
这不行。当我以客户
登录时, products_path
仍然指向 Admins :: ProductsController#index
因为它是第一个定义。
This doesn't work. When I login as a Customer
, products_path
still points to Admins::ProductsController#index
as it is the first defined.
任何线索?
更新
根据代码,这是不可行的。
推荐答案
事实证明,使用路由约束的最佳方式是:
It turns out the best way to achieve that is to use routing constraints as such:
# config/routes.rb
resources :products, module: 'customers', constraints: CustomersConstraint.new
resources :products, module: 'admins', constraints: AdminsConstraint.new
# app/helpers/customers_constraint.rb
class CustomersConstraint
def matches? request
!!request.env["warden"].user(:customer)
end
end
# app/helpers/admins_constraint.rb
class AdminsConstraint
def matches? request
!!request.env["warden"].user(:admin)
end
end
我将约束对象存储在帮助文件夹中,因为我真的不知道放置它们的最佳位置。
I stored the constraint objects in the helper folder because I don't really know the best place to put them.
感谢 @crackofdusk 的提示。
这篇关于Rails,Devise:相同的资源,基于用户类型的不同的控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!