微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

html – 如何在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增量?

解决方法:

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] 举报,一经查实,本站将立刻删除。

相关推荐