本文介绍了创建或覆盖Rails Active Record宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Rails应用程序中,Active Record通过宏来创建created_atupdated_at列(似乎也称为魔术列").

In a Rails app, Active Record creates created_at and updated_at columns thank to macros, (it seems to be also called "magic columns").

请参见活动记录迁移

我对这种机制有疑问:

  • 是否可以覆盖它以获得第三列(例如deleted_at)?
  • 是否可以创建一个新的宏t.publishing来创建publish_uppublish_down列?例如
  • 在哪里编写代码?
  • 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 create publish_up and publish_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.

在Rails 4上工作.

Working on Rails 4.

推荐答案

ActiveRecord::ConnectionsAdapters::TableDefinition::Table类负责所有高级迁移,例如columnindexindex_exists?等.它具有timestamps方法,可为您添加created_atupdated_at列:

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

创建新宏同样如此:

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

检出类源代码在github上获得更多见解.

Check out the class source code at github for more insights.

这篇关于创建或覆盖Rails Active Record宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 20:20