Q:

Generating a custom id on model create

I'm trying to generate a custom ID for my model based on the database ID the is assigned by default in Rails.
That is, I have the following model:
class Teacher < ActiveRecord::Base
end

When saved, a Teacher gets an id automatically from the database. I've added another column called user_id which is a string; I'm trying to generate a new id that's based on the default one (i.e. if the teacher.id is 1, then the user_id becomes T-0001 or something to that effect.
I've tried using the after_save method; but that isn't very helpful; I would end up updating the new column even if I didn't need to (say after an update or something). The after_create callback won't work either as the id hasn't actually been assigned yet by the database.

A:

Why not, instead of storing it in your database, you just create a method that retuns that value? Something like:
class Teacher < ActiveRecord::Base
  ...
  def user_id
    "T-#{self.id.to_s.rjust(4, '0')}"
  end
end

If you really want to store it in the database, you should use after_save checking if the value already was generated:
class Teacher < ActiveRecord::Base
  after_save :generate_user_id
  ...
  private
  def generate_user_id
    self.update(user_id: "T-#{self.id.to_s.rjust(4, '0')}") if self.user_id.nil?
  end
end

