Rails:使用具有单表继承的设计 [英] Rails: Using Devise with single table inheritance

查看:30
本文介绍了Rails:使用具有单表继承的设计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在让 Devise 以我想要的单表继承方式工作时遇到问题.

I am having a problem getting Devise to work the way I'd like with single table inheritance.

我有两种不同类型的帐户,其组织方式如下:

I have two different types of account organised as follows:

class Account < ActiveRecord::Base
  devise :database_authenticatable, :registerable
end

class User < Account
end

class Company < Account
end

我有以下路线:

devise_for :account, :user, :company

用户在 /user/sign_up 注册,公司在 /company/sign_up 注册.所有用户都使用 /account/sign_in 中的单个表单登录(Account 是父类).

Users register at /user/sign_up and companies register at /company/sign_up. All users log in using a single form at /account/sign_in (Account is the parent class).

但是,通过此表单登录似乎只是对 Account 范围内的用户进行身份验证.对 /user/edit/company/edit 等操作的后续请求将用户定向到相应范围的登录屏幕.

However, logging in via this form only seems to authenticate them for the Account scope. Subsequent requests to actions such as /user/edit or /company/edit direct the user to the login screen for the corresponding scope.

如何让 Devise 识别帐户类型"并针对相关范围对其进行身份验证?

How can I get Devise to recognise the account 'type' and authenticate them for the relevant scope?

非常感谢任何建议.

推荐答案

我刚刚遇到了问题中概述的确切场景(更改了类名).这是我的解决方案(设计 2.2.3,Rails 3.2.13):

I just ran into the exact scenario (with class names changed) as outlined in the question. Here's my solution (Devise 2.2.3, Rails 3.2.13):

在 config/routes.rb:

in config/routes.rb:

devise_for :accounts, :controllers => { :sessions => 'sessions' }, :skip => :registrations
devise_for :users, :companies, :skip => :sessions

在 app/controllers/sessions_controller.rb 中:

in app/controllers/sessions_controller.rb:

class SessionsController < Devise::SessionsController
    def create
        rtn = super
        sign_in(resource.type.underscore, resource.type.constantize.send(:find, resource.id)) unless resource.type.nil?
        rtn
    end
end

注意:由于您的 Accounts 类仍将是可注册的,因此 views/devise/shared/_links.erb 中的默认链接将尝试发出,但 new_registration_path(Accounts) 将不起作用(我们:在路由中跳过它绘图)并导致错误.您必须生成设计视图并手动将其删除.

Note: since your Accounts class will still be :registerable the default links in views/devise/shared/_links.erb will try to be emitted, but new_registration_path(Accounts) won't work (we :skip it in the route drawing) and cause an error. You'll have to generate the devise views and manually remove it.

帽子提示 https://groups.google.com/forum/?fromgroups=#!topic/plataformatec-devise/s4Gg3BjhG0E 为我指明了正确的方向.

Hat-tip to https://groups.google.com/forum/?fromgroups=#!topic/plataformatec-devise/s4Gg3BjhG0E for pointing me in the right direction.

这篇关于Rails:使用具有单表继承的设计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆