Ruby on rails 为什么在生成模型时会创建时间戳
创建以下迁移脚本Ruby on rails 为什么在生成模型时会创建时间戳,ruby-on-rails,Ruby On Rails,创建以下迁移脚本 rails generate model User email:string password:string class CreateUsers
rails generate model User email:string password:string
class CreateUsers
什么是时间戳?为什么我没有要求创建时间戳?Rails会自动在表/migration/ActiveRecord模型中添加两列,
created\u at
和Update\u at
。如果你不想要它们,你可以移除它们
Rails擅长的是自动为你做一些你“没有要求”的事情:这是“配置之上的约定(CoC)”。你(几乎)总是可以指定你想要别的东西,但一般来说,Rails会按照大多数用户想要的方式做事情
创建和更新的时间戳通常非常有用。时间戳是迁移中的一种方法,它将在模型的相应表中创建两列 例:根据你的例子
- 模块是用户
- 表是用户
如果您不希望有这些列,只需从迁移中删除“timestamps”方法。在搜索“生成不带时间戳的rails模型”时,出现了这个问题,因此我想添加一个关于如何做到这一点的答案:
rails g model MyModel——没有时间戳
这适用于Rails 3.2+。我正在使用Rails 4.2.5,现在您可以选择是否需要时间戳字段
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
class CreateProducts
上述迁移将创建一个名为create_products的表,其中包含两个时间戳字段(created_at和updated_at)。如果不需要这些字段,则需要删除时间戳行
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.text :description
t.timestamps null: false
end
end
end
class CreateProducts
来源:t.timestamps是单个字段还是映射到您拥有的上述列mentioned@Jason:这两者都产生。
class CreateProducts < ActiveRecord::Migration
def change
create_table :products do |t|
t.string :name
t.text :description
end
end
end