我正在进行迁移,并删除每个表的默认'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错误:
MySQL 2::error : SQL语法出现错误;请检查与MySQL服务器版本相对应的手册,以获得正确的语法,以便在第1行使用接近“students.student_id增量1 STA所拥有的序列students_student_id_seq”。
如何在Rails 5中自动生成带有起始值的自定义id增量?
发布于 2017-01-25 11:57:46
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
endhttps://stackoverflow.com/questions/41850902
复制相似问题