how to add current time as default value

1,465 views
Skip to first unread message

Rajkumar Surabhi

unread,
Mar 19, 2010, 4:16:56 AM3/19/10
to rubyonra...@googlegroups.com
hi all,

by using timestamps we can create created_at and updated_on columns to
our tables. But i dont wnat the columns in my table and i want to add my
own column which datatype is timestamp and that must take
current_timestamp or now as default value.


how to do it


re
--
Posted via http://www.ruby-forum.com/.

Loganathan Ganesan

unread,
Mar 19, 2010, 5:14:52 AM3/19/10
to rubyonra...@googlegroups.com
Rajkumar Surabhi wrote:
> hi all,
>
> by using timestamps we can create created_at and updated_on columns to
> our tables. But i dont wnat the columns in my table and i want to add my
> own column which datatype is timestamp and that must take
> current_timestamp or now as default value.
>
>
> how to do it
>
>
> re

Since we cannot specify the now() function in the :default option in the
migration file, we can achieve this requirement using the following:

# Sample code
class Samples < ActiveRecord::Migration
def self.up
create_table :system_settings do |t|
t.text :value
t.string :type
t.timestamp :created_time
end
execute "ALTER TABLE system_settings ALTER created_time SET
DEFAULT now()"
end

def self.down
end
end

kannav rajeev

unread,
Mar 19, 2010, 5:22:51 AM3/19/10
to rubyonra...@googlegroups.com
Time.now

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonra...@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.




--
Thanks:
Rajeev sharma

JoeEd E.

unread,
Jul 1, 2013, 11:42:16 PM7/1/13
to rubyonra...@googlegroups.com
If Loganathan's answer does not work, try this:

I had to use

execute "ALTER TABLE system_settings ALTER created_time SET
DEFAULT CURRENT_TIMESTAMP"

(instead of NOW())

JoeEd E.

unread,
Jul 2, 2013, 12:02:20 AM7/2/13
to rubyonra...@googlegroups.com
Okay, so it turns out that does not work either. Here is the actual
syntax:

execute "ALTER TABLE tablename CHANGE column_name column_name
TIMESTAMP DEFAULT CURRENT_TIMESTAMP"

You have to put the column name in twice as well as specify the datatype
again.

Also, you may be wondering why I am responding to a 7 year old
question... I came across it on google and there was NOTHING else out
there to help with this issue. Yes, I know Rails creates timestamps for
you. However, when you are polling a database that can have information
entered from other sources, it is useful to be able to do this.
Reply all
Reply to author
Forward
0 new messages