2017-01-25 6 views
4

こんにちは、私は移行に取り組んでおり、各テーブルのデフォルト'id'を削除します。私は'student_id'代わりに特別なフィールドを作成し、私はそれがここに1001Ruby on Rails 5でカスタムIDを自動的に開始値でインクリメントする方法は?

で始まる自動インクリメントが私のコードだようにしたい:

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でカスタム値をインクリメントするには?

答えて

3
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 
+0

これはすべてですか?またはstudent_idフィールドを特定のものにする必要がありますか?私はそれをマイグレーションした後にレコードを追加しようとしましたが、ロールバックしています。 –

+0

私はそのテーブルのPKを設定する必要があると思います。 –

+0

あなたはそのフィールドへのインデックスを意味しますか?このようにadd_index( "students"、 "student_id")??? –

関連する問題