创建或覆盖Rails Active Record宏
在Rails应用程序中,Active Record创建created_at
和updated_at
列感谢宏(它似乎也被称为“魔术列”)。
请参阅Active Record Migrations
我对这种机制有一些疑问:
- 是否可以覆盖它以获得第三列(例如
deleted_at
)? - 例如,是否可以创建一个新的宏
t.publishing
来创建publish_up
和publish_down
列? - 在哪里编码?
显然,我知道我可以手动添加这些列,但我想知道如何用宏来实现它。
在Rails上工作4。
ActiveRecord::ConnectionsAdapters::TableDefinition::Table
类负责所有高级迁移,如column
, index
, index_exists?
等等。 它有timestamps
方法,为您添加created_at
和updated_at
列:
# 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
基本上,你可以用这种方式对它进行monkeypatch(在你的初始化器中的某个地方):
class ActiveRecord::ConnectionsAdapters::TableDefinition::Table def timestamps @base.add_timestamps(@table_name) @base.add_column(@table_name, :deleted_at, :datetime) end end
这同样适用于创建新宏:
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
在那之后,你应该能够做这些事情:
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
查看github上的类源代码以获取更多见解。