首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在Rails 5中自动增加具有起始值的自定义id?

如何在Rails 5中自动增加具有起始值的自定义id?
EN

Stack Overflow用户
提问于 2017-01-25 11:50:17
回答 1查看 2.3K关注 0票数 5

我正在进行迁移,并删除每个表的默认'id'。我创建了一个特殊的字段,而不是'student_id',我希望使它从1001开始自动递增。

这是我的代码:

代码语言:javascript
复制
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增量?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-01-25 11:57:46

代码语言:javascript
复制
execute "CREATE SEQUENCE students_student_id_seq OWNED BY students.student_id INCREMENT BY 1 START WITH 1001"

以上是Postgresql语法,您的数据库似乎是MySQL。

无论如何,您可以通过将student_id设置为主键,然后更新增量起始值来实现您想要的结果。

代码语言:javascript
复制
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
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41850902

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档