IRB Rocks!

# Hack your code

Determine if model is just created

Sometimes we need to know if a model is just created after save if for first time. Rails doesn't provide a method to check this situation, so we need to use a small trick.

If we have timestamps (specifically created_at and update_at) columns defined in this model, we can use it:

class User < ActiveRecord::Base

  # ...

  #
  # Check if the current user is just created.
  #
  # == Returns:
  # Boolean
  #
  def just_created?
    created_at == updated_at
  end
end

As you can see, I compare the date of creation and update. If we don't have these columns defined, we can take advantage of before_create callback to check if our User is just created.

class User < ActiveRecord::Base

  # ...

  before_create :set_just_created

  #
  # Check if the current user is just created.
  #
  # == Returns:
  # Boolean
  #
  def just_created?
    @just_created || false
  end

  private

  #
  # Set a flag indicating this model is just created
  #
  def set_just_created
    @just_created = true
  end
end

Before create the User, I set the flag I will use.

As usual, all the code is available in Github ;).

gem share .gem