问题
In a Rails app, Active Record creates created_at
and updated_at
columns thank to macros, (it seems to be also called "magic columns").
See Active Record Migrations
I have some questions about that mecanism:
- Is it possible to override that to get a third column (e.g.
deleted_at
) ? - Is it possible to create a new macro
t.publishing
that will createpublish_up
andpublish_down
columns, for example? - And where to code that?
Obviously, I know I can add those columns manually, but I wonder how to achieve it with macros.
Working on Rails 4.
回答1:
ActiveRecord::ConnectionsAdapters::TableDefinition::Table
class is responsible for all the high-level migrations stuff like column
, index
, index_exists?
and so on. It has timestamps
method which adds created_at
and updated_at
columns for you:
# Adds timestamps (+created_at+ and +updated_at+) columns to the table.
# See SchemaStatements#add_timestamps
# t.timestamps
def timestamps
@base.add_timestamps(@table_name)
end
Basically, you could monkeypatch it in this way (somewhere in your initializers):
class ActiveRecord::ConnectionsAdapters::TableDefinition::Table
def timestamps
@base.add_timestamps(@table_name)
@base.add_column(@table_name, :deleted_at, :datetime)
end
end
The same applies to creating a new macro:
class ActiveRecord::ConnectionsAdapters::TableDefinition::Table
def publishing
@base.add_column(@table_name, :publish_up, :datetime)
@base.add_column(@table_name, :publish_down, :datetime)
end
end
After that, you should be able to do these things:
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :first_name
t.string :last_name
t.timestamps
t.publishing
end
end
def self.down
drop_table :users
end
end
Check out the class source code at github for more insights.
来源:https://stackoverflow.com/questions/24201039/create-or-override-rails-active-record-macros