2
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?

1 Answer 1

2

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.

2
  • this would be one way to go, but it means that it will get called on every cretate/update, when it's only necessary on create Commented Oct 24, 2017 at 13:38
  • 1
    In such case you can use before_create callback right? Commented Oct 24, 2017 at 18:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.