简体   繁体   English

created_at 和 updated_at 列从何而来?

[英]Where do the created_at and updated_at columns come from?

All the tables in the database created by a rails application seem to have created_at and updated_at columns. rails 应用程序创建的数据库中的所有表似乎都有 created_at 和 updated_at 列。 What creates these?是什么创造了这些? Are they optional, or does something internal rely on them?它们是可选的,还是内部依赖于它们?

They are created by default when you run the ActiveRecord migration for a model.它们是在您为模型运行 ActiveRecord 迁移时默认创建的。 ActiveRecord automatically populates/updates them when you create or update a model instance (and thus the underlying database table row) respectively.当您分别创建或更新模型实例(以及底层数据库表行)时,ActiveRecord 会自动填充/更新它们。

You can remove the columns by removing the t.timestamps line from within the model migration file.您可以通过从模型迁移文件中删除t.timestamps行来删除列。

In your database migration for every table you have something like t.timestamps .在每个表的数据库迁移中,您都有类似t.timestamps Remove this from your migration and your database columns created_at and updated_at won't be created.从您的迁移中删除它,您的数据库列 created_at 和 updated_at 将不会被创建。

Edit:编辑:

In case you need to create a new migration to remove those columns you can use remove_timestamps or remove_column如果您需要创建新的迁移来删除这些列,您可以使用remove_timestampsremove_column

remove_timestamps definition shows how you can use remove_column if you want to. remove_timestamps定义显示了如何使用remove_column如果需要)。

def remove_timestamps(table_name, **options)
  remove_column table_name, :updated_at
  remove_column table_name, :created_at
end

补充八达通所说的,它们是可选的,用于跟踪相应表中的记录创建和更新日期时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM