为什么在生成模型时会创建时间戳

时间:2011-09-10 08:38:02

标签: ruby-on-rails

rails generate model User email:string password:string

创建以下迁移脚本

class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :email
      t.string :password
      t.timestamps
    end
  end
  def self.down
    drop_table :users
  end
end

什么是时间戳,为什么它被创建,当我没有要求创建时?

4 个答案:

答案 0 :(得分:24)

这个问题出现在搜索“生成没有时间戳的轨道模型”中,所以我想补充一下如何做到这一点:

rails g model MyModel --no-timestamps

这适用于Rails 3.2 +。

答案 1 :(得分:11)

Rails会自动向您的table / migration / ActiveRecord模型添加两列created_atupdated_at。如果您不想要它们,可以将它们删除。

自动为你做“你没有问过”的东西是Rails擅长的:这是“约定优于配置(CoC)”。你可以(几乎)总是指定你想要别的东西,但一般来说,Rails会像大多数用户想要的那样做。

创建和更新的时间戳通常非常有用。

答案 2 :(得分:2)

时间戳是迁移中的一种方法,它会在模型​​的相应表中创建两列。

例如:根据你的例子

  • 模块是用户
  • 表是用户

在users表中,它将创建两个日期时间列:

  1. created_at
  2. 的updated_at
  3. 当您创建对象或编辑对象时,这些列将自动更新,在本例中为用户模型(当您通过ActiveRecord模型执行任何操作时)。

    这在调查记录创建/更新时间时非常有用。

    如果您不希望拥有这些列,请从迁移中删除“timestamps”方法。

答案 3 :(得分:0)

我正在使用Rails 4.2.5,现在您可以选择是否需要时间戳字段。

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.text :description

      t.timestamps null: false
    end
  end
end

上述迁移将创建一个名为create_products的表,其中包含两个时间戳字段(created_at和updated_at)。如果您不希望这些字段需要删除时间戳行。

class CreateProducts < ActiveRecord::Migration
  def change
    create_table :products do |t|
      t.string :name
      t.text :description
    end
  end
end

来源:http://edgeguides.rubyonrails.org/active_record_migrations.html