设计中的多个模型上的相同current_user
问题
我有一个User模型,以及inheritance自User模型的Volunteer模型:
class User < ActiveRecord::Base end class Volunteer < User end
它们都保存在数据库中的同一个表中,但具有不同的控制器/路由。
路线是:
devise_for :users .... devise_for :volunteers ....
这工作正常,花花公子,但我使用的授权系统依赖于current_user
帮助器。 这对于志愿者来说是失败的,因为设计为志愿者模型创造了当前的志愿者。
我试过的是设置devise_for :volunteers, :singular => "user"
,这会创建一个指向用户和志愿者的current_user,但现在的问题是志愿者的路线搞砸了。
题
所以我的问题是,有没有办法获得current_user
助手,引用除用户以外的其他模型?
我认为这样您就允许用户在同一会话中以用户和Voluteer的身份登录。
一旦你有办法解决这个问题,你就不会有
# in application_controller.rb alias_method :devise_current_user, :current_user def current_user devise_current_user || current_volunteer end
在你的application_controller.rb中
我遇到了类似的问题并且像这样解决了。 但这个解决方案是否适用于康康gem。
application_controlller.rb
def actual_user @actual_user ||= current_user.present? ? current_user : current_volunteer end def current_ability @current_ability ||= Ability.new(actual_user) end
我接受了viktor tron的回答,因为这似乎是最干净的方法。
但是,我以不同的方式解决了我的问题。
我最终将其他类的登录过程硬编码为:user
。 这使我可以访问current_user
方法,即使是志愿者课程也是如此。
class Volunteers::SessionsController < Users::SessionsController def create resource = warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#new") if resource flash[:notice] = "You are logged in" sign_in(:user, resource) super else super end end end
也许有点迟到但你可以在你的routes.rb中尝试以下
devise_for :users , :skip => :registrations as :user do match "volunteers/edit(.:format)", :to => "devise/registrations#edit" end devise_for :volunteers , :skip => :sessions
上面的代码假定所有用户及其子类(假设您正在实现STI以实现用户模型层次结构)可以sign_in和sign_out,但只有志愿者可以注册。 由于志愿者是用户,因此用户应该能够编辑他的注册。 您可以在as:user块中添加更多路由。