2014-06-13 63 views
2

在Rails应用程序中,Active Record创建了created_atupdated_at列,感谢宏(它似乎也称为“魔术列”)。创建或覆盖Rails Active Record宏

Active Record Migrations

我有关于mecanism一些问题:

  • 是否有可能重写获得第三列(例如deleted_at)?
  • 是否有可能创建一个新的宏t.publishing,它将创建​​和publish_down列,例如?
  • 并在哪里编码?

很明显,我知道我可以手动添加这些列,但我不知道如何用宏实现它。

工作on Rails的4

回答

3

ActiveRecord::ConnectionsAdapters::TableDefinition::Table类负责所有的高级别迁移的东西像columnindexindex_exists?等。它有timestamps方法,增加了created_atupdated_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 

基本上,你可以(在你的初始化某处)这样猴补丁吧:

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上的类source code了解更多见解。

+0

谢谢你的帮助。我通过monkeypatching TableDefinition类来工作https://gist.github.com/jocelynduc/3a34478ed3e7da3a0dcb – Jocelyn