MST
星途 面试题库

面试题:Ruby中如何使用ActiveRecord进行数据库表的创建

假设你正在使用Ruby的ActiveRecord库与数据库交互,现有一个需求是创建一个名为`users`的表,该表包含`name`(字符串类型)、`age`(整数类型)和`email`(字符串类型)字段。请用Ruby代码展示如何使用ActiveRecord迁移来创建此表。
12.1万 热度难度
编程语言Ruby

知识考点

AI 面试

面试题答案

一键面试
class CreateUsers < ActiveRecord::Migration[6.0]
  def change
    create_table :users do |t|
      t.string :name
      t.integer :age
      t.string :email

      t.timestamps
    end
  end
end

上述代码中:

  1. CreateUsers 是迁移类,继承自 ActiveRecord::Migration,方括号内的 6.0 表示使用的 Rails 版本(根据实际情况可能会不同)。
  2. change 方法定义了迁移的具体操作,这里使用 create_table 创建 users 表。
  3. create_table 块内,使用 t.string 定义字符串类型字段 nameemail,使用 t.integer 定义整数类型字段 age
  4. t.timestamps 会自动添加 created_atupdated_at 两个时间戳字段。