Create or override Rails Active Record macros

独自空忆成欢 提交于 2019-12-07 21:24:42

问题


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 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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!