Search code examples
ruby-on-railsactiverecorddevisedevise-invitable

Replacing default id for rails with a custom id


Rails 5.1
Devise
Devise Invitable

In models/concerns/shared.rb, I have:

module Shared

  extend ActiveSupport::Concern

  def generate_model_id
    self.id = "#{self.class.name}.#{Time.now.to_f.to_s}" if id.blank?
  end  

In my create_usres migration file, I have:

class DeviseCreateUsers < ActiveRecord::Migration[5.1]
  def change
    create_table :users, id: false  do |t|
      t.column :id, :primary_string

In my models/user.rb, I have:

class User < ActiveRecord::Base

  include Shared

  enum role: [:user, :vip, :admin]
  after_initialize :set_default_role, :if => :new_record?

  devise :invitable, :database_authenticatable, :registerable,
        :recoverable, :rememberable, :trackable, :validatable

In my seeds.rb file, I have:

user = User.new(
    :email =>'[email protected]',
    :password =>'xK#986754',
    :password_confirmation =>'xK#986754',
    :first_name =>'John',
    :last_name =>'Doe',
    :role => 1,
    :approved => true
)
user.skip_invitation
user.save         

I have exported all the Devise models (confirmations, invitations, passwords, registrations, sessions, unlocks), and put the corresponding controllers under the controllers/users folder.

Which controller do I call the generate_model_id method from, and where?


Solution

  • I hope this you can do in the module that you have created - shared.rb by using active record callbacks.

    module Shared
      extend ActiveSupport::Concern
    
      included do
        before_save :generate_model_id
      end
    
      def generate_model_id
       self.id = "#{self.class.name}.#{Time.now.to_f.to_s}" if id.blank?
      end
    end
    

    read more about active support callbacks here.

    Related SO question thanks.