如何在Ruby on Rails 5中以起始值自动递增自定义ID?

用户名

大家好,我正在进行迁移,因此我删除了'id'每个表的默认设置我创建了一个特殊字段,'student_id'并希望使其从1001开始自动递增。

这是我的代码:

class CreateStudents < ActiveRecord::Migration[5.0]
  def up
    create_table :students, :id => false do |t|
      t.integer "student_id"
      t.string "first_name", :limit => 25
      t.string "last_name", :limit => 50
      t.string "email", :default => ' ', :null => false
      t.string "birthday"
      t.string "subjects"
      t.string "teachers"
      t.string "username", :limit => 25
      t.string "password_digest", :limit => 40
      t.timestamps
    end
    execute "CREATE SEQUENCE students_student_id_seq OWNED BY students.student_id INCREMENT BY 1 START WITH 1001"
  end

  def down
  drop_table :students
  execute "DELETE SEQUENCE students_student_id_seq"
  end

end

我收到了ff错误:

Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SEQUENCE students_student_id_seq OWNED BY students.student_id INCREMENT BY 1 STA' at line 1

如何在Ruby on Rails 5中自动使用起始值自定义id增量?

米海·丁库列斯库(Mihai Dinculescu)
execute "CREATE SEQUENCE students_student_id_seq OWNED BY students.student_id INCREMENT BY 1 START WITH 1001"

上面是Postgresql语法,您的数据库似乎是MySQL。

无论如何,您可以通过设置student_id为主键并更新增量起始值来实现所需的功能。

def change
  create_table :students, :id => false do |t|
    t.integer "student_id", primary_key: true
    t.string "first_name", :limit => 25
    t.string "last_name", :limit => 50
    t.string "email", :default => ' ', :null => false
    t.string "birthday"
    t.string "subjects"
    t.string "teachers"
    t.string "username", :limit => 25
    t.string "password_digest", :limit => 40
    t.timestamps
  end

  reversible do |dir|
    dir.up { execute "ALTER TABLE students AUTO_INCREMENT = 1000" }
  end
end

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何在 Ruby on rails 中连接 Mercadopago

如何在Ruby on Rails中修补猴子

如何在Ruby on Rails中启用压缩?

如何在Ruby on Rails中实现RESTful?

如何在 Ruby on Rails 中连接模型

如何在Ruby on Rails中实现CardDAV

如何在Ruby on Rails中添加自定义路线,控制器和动作?

如何在 Ruby on Rails 应用程序中实现自定义 css?

Ruby On Rails:如何在Rails中撤消nested_scaffold

如何在Rails中的ruby中实现哈希值

如何在 Ruby on Rails 中显示此数组中的值

如何在Ruby on Rails中的params数组中更改值?

如何在Rails 6上的ruby中重置主键ID?

如何在 Ruby on Rails 中检索链接的值

ruby on rails slim如何在select中处理值

如何在Ruby on Rails 5中验证pg数组的长度?

Ruby on Rails:基于另一个字段的自定义字母数字id并自动对其进行递增

如何在SQLAlchemy for SQLServer中的ID列中定义起始值?

在Ruby on Rails中自定义表示对象ID的格式

Ruby on Rails:如何在Heroku上运行自动耙任务

如何在 Ruby on Rails 中合并列中的重复项?

如何在Rails中的ruby中实现递归删除?

如何在 Ruby on Rails 中编写测试用例

如何在Ruby on Rails代码中捕获Zlib :: BufError?

如何在Ruby on Rails中实现复杂的SQL查询?

如何在Ruby on Rails中传递控制器参数

如何在Ruby on Rails中遍历自引用模型

我应该如何在Rails中实现我的Ruby代码?

如何在 Ruby on rails 中创建动态哈希数组