gpt4 book ai didi

html - 如何在 Ruby on Rails 5 中使用起始值自动增加自定义 ID?

转载 作者:可可西里 更新时间:2023-11-01 07:34:13 24 4
gpt4 key购买 nike

我正在进行迁移,我删除了每个表的默认 '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?

最佳答案

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

关于html - 如何在 Ruby on Rails 5 中使用起始值自动增加自定义 ID?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41850902/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com