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?
When you add a new model to a Rails application, it generates a migration to create the corresponding table for you. If that’s not what you need, you can write your own.
$ rails g model user email This command will generate user model with email field type of string, migration which creates users table, test for model and factory (if you have it). You are able to generate model with few fields like this: $ rails g model user first_name last_name email
We want to add users to the todo application, so we need to add a username to each record. First, create a migration: As the command line implies, this tells Rails to generate a migration for us. It does all the work for us. Let’s run this and see what happens:
Column changes, however, aren’t reversible. Adding a new class to an application is a frequent change too. When you add a new model to a Rails application, it generates a migration to create the corresponding table for you. If that’s not what you need, you can write your own.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With