How to automatically increase user id with initial value in Ruby on Rails 5?

Hi guys, I am working on a wrapping and I am deleting the default 'id'for each table. Instead, I created a special field 'student_id', and I want to make it an automatic increment, starting from 1001.

here are my codes:

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

I got ff error:

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

How do I set auto-add user id with initial value in Ruby on Rails 5?

+4
source share
1 answer
execute "CREATE SEQUENCE students_student_id_seq OWNED BY students.student_id INCREMENT BY 1 START WITH 1001"

The above syntax is Postgresql and your database seems like 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
+3

Source: https://habr.com/ru/post/1667757/


All Articles