Search code examples
ruby-on-railsauthenticationdeviseruby-on-rails-3

How can I configure Devise for Ruby on Rails to store the emails and passwords somewhere other than in the user model?


I'd like to store emails in a separate table and allow users to save multiple emails and log in with any of them. I'd also like to store passwords in a different table.

How can I configure Devise to store authentication info elsewhere?

Worst case scenario, if I just have to hack into it, is there a generator to just port everything over to the app? I noticed there was a generator for the views.


Solution

  • To do this, you have just to set up your models properly, create your email association. Also you have to override the user finder method from devise, to do this you have to override self.find_for_database_authentication(conditions) method.

    class User < ActiveRecord::Base
      has_many :emails
      accepts_nested_attributes_for :emails
      ...
      def self.find_for_database_authentication(conditions)
        email = conditions.first
        self.where(:emails=>{:name=>email})
      end
    end
    

    Also you have to add the emails to your devise.rb to use it.

    Devise.setup do |config|
      ...
      config.authentication_keys = [ :emails ]
      ...
    end
    

    Update

    First question: Yes, the method from the devise will bee overrided automatically.

    Second question: You should have your_application_path/config/initializers/devise.rb I think it's created when you use the devise gem. If you don't have you can create it. The content I specified is good, just omit the dots (...)