我正在进行迁移,并且删除了每个表的默认'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错误:

如何在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?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41850902/

10-09 23:58