Henley Wing Chiu
Henley Wing Chiu

Reputation: 22515

How to set default value of column to current time with ActiveRecord?

I got a field in MYSQL called "date_added". I want this to have the value Time.now.to_i as its default value (in other words, the time the record was added). I know a similar column is added for free in ActiveRecord, but ignoring that... how can I add this default value?

:default => ???

Upvotes: 1

Views: 529

Answers (1)

Ben Lee
Ben Lee

Reputation: 53319

You can use before_create:

class SomeModel < ActiveRecord::Base
  before_create :set_date_added

  protected

  def set_date_added
     self.date_added = Time.now.to_i
  end
end

This gets called right before an object is saved for the first time, exactly the conditions you want.

Alternatively, you can use a hack to rename the default activerecord created_at to date_added by following the answers here: Renaming the created_at, updated_at columns of ActiveRecord/Rails See http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html for more information on callbacks.

Upvotes: 3

Related Questions