大家好,我正在进行迁移,因此我删除了'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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句