html – 如何在Ruby on Rails 5中使用起始值自动增加自定义ID?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了html – 如何在Ruby on Rails 5中使用起始值自动增加自定义ID?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1713字,纯文字阅读大概需要3分钟。
内容图文
大家好我正在进行迁移,我删除了每个表的默认’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?全部内容,希望文章能够帮你解决html – 如何在Ruby on Rails 5中使用起始值自动增加自定义ID?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。