Search code examples
rubydevisemodel-associations

How do you add new column named "unique_id", and associate mailboxer with devise?


I have a question. Devise and mailboxer are installed on my rails app without any problem.

The problem is that you have to use "email" or "name" column to associate devise user with mailboxer. Obviously, devise doesn't have column called "name" in Users table. So, if you use "email" then users will see everyone else's email address that they wanna hide.

I want twitter-like registration. They've got unique_id(account name) that never will be changed. To achieve that, How can I?

I. Add column named "unique_id" to Users table? command: rails g migration AddUniqueIdToUsers unique_id:string to create migration file, and open and edit like this

class AddUniqueIdToUsers < ActiveRecord::Migration  
   def change  
    add_column :users, :unique_id, :string  
    add_index :users, :unique_id,  :unique => true  
   end 
end

II. How do I associate devise with mailboxer by using "unique_id" column?

Thanks in advance


Solution

  • Obviously, devise doesn't have column called "name" in Users table

    That is entirely up to you, all Devise does (or wants you to do) is add a few records that tell it how to function. If you look at the devise generator you can see that all it does is add a couple of columns to your migration.

    I want twitter-like registration. They've got unique_id(account name) that never will be changed. To achieve that, How can I?

    First of all, a unique ID is always given to you by free in Rails (indeed, in most typical web applications using a database backend, each row has a unique ID).

    But, if you also want users to select a username, and have that be unique as well, the you could do as the mailboxer readme states and simply override the usage of name with your own database column like username, like so:

    Mailboxer.setup do |config|
      # ...
      #Configures the methods needed by mailboxer
      config.email_method = :email
      config.name_method = :username
      # ...
    end
    

    Or, if you want to stay out of the mailboxer config file, you can simply use alias_method and do this (given that you have a username column):

    class User < ActiveRecord::Base
      alias_method :name, :username
      acts_as_messageable
    end
    

    Either way, Devise doesn't restrict you in which columns you use on your User model, and it seems that Mailboxer also doesn't restrict you in which columns you use to attach the gem to the User model. So you have as much flexibility as you want without having to built this functionality by yourself.