ruby on rails - activerecord/pg: support automatic timestamps in DDL -
updated (to show code)
i'd mimic activerecord's automatic timestamps directly in database, without explicitly adding logic after every migration's create_table()
call.
here's now:
class statusquo < my::migration::subclass def self.up create_table :tbl |t| ... columns ... t.timestamps end add_default_now(:tbl, :created_at) # alter column ... default now() add_default_now(:tbl, :updated_at) # alter column ... default now() add_updated_at_trigger(:tbl) # before update on ... trg_updated_at() end end
by contrast, here's i'd do:
class druthers < my::migration::subclass def self.up create_table :tbl |t| ... columns ... t.timestamps end end end
is there easy or recommended way accomplish this? using activerecord 3, postgresql 8.4.
here's best come far, full source here:
in config/environment.rb
check see if our connection adapter postgresql. if so, require
file following:
- wrap
columndefinition#to_sql
force defaultsforce "created_at" , "updated_at" have default current_timestamp
- wrap
create_table
conditionally apply triggerif newly created table has "updated_at" column, install trigger referencing database function assumed exist.
not pretty (need have maintain function definition outside of code) , not complete (change_table
won't handle introducing timestamps properly), enough.
Comments
Post a Comment