user984621
user984621

Reputation: 48443

Rails - how to add timestamps to a model?

I have an exist model (and table) with these columns: id, name, city. In this table are data and I would like to this table add the columns created_at and updated_at - could anyone give me a help, how to do it? I mean - if I create a model, so these two columns are created automatically and the time informations are inserted always automatically, when I save there something.

Is possible now to add these two columns with automatic inserting time-data?

Upvotes: 5

Views: 8891

Answers (3)

maček
maček

Reputation: 77778

This should allow you to add timestamp columns to an already existing model

rails generate migration add_timestamps_to_users

This will create a migration file for you. Open it up and make necessary changes

class AddTimestampsToUsers < ActiveRecord::Migration
  # in my example i'm using `users` table; change this to match your table name
  def change_table :users do |t|
    t.timestamps
  end
end

Then migrate your database

rake db:migrate

Upvotes: 13

Jan Klimo
Jan Klimo

Reputation: 4930

add_timestamps is a dedicated method for this purpose:

class AddTimestampsToUsers < ActiveRecord::Migration
  def change
    add_timestamps :users
  end
end

Upvotes: 12

exterm
exterm

Reputation: 399

It should be noted that while maček's answer is right at the core, he doesn't use the correct syntax for migrations (forgot the "change" method).

So here is his answer with corrected syntax:

This should allow you to add timestamp columns to an already existing model

rake generate migration add_timestamps_to_users

This will create a migration file for you. Open it up and make necessary changes

class AddTimestampsToModel < ActiveRecord::Migration
  # in my example i'm using `users` table; change this to match your table name
  def change
    change_table :users do |t|
      t.timestamps
    end
  end
end

Then migrate your database

rake db:migrate

Upvotes: 14

Related Questions