2016-04-07 16 views
0

私はこのフォーラムで利用できるほぼすべての回答を試みましたが、何も助けになりませんでした。Mysql2 ::エラー:Railsを使用してキー 'PRIMARY'の重複エントリ '2016'

私の学生はすべて、このフォーマットのトラッキングID:2016-N-XXXX(any four digit number)を持っています。

私はこの形式のIDを持つ生徒を追加しようとするとこのエラーを出す "学生フォームを追加"しています。

マイ "学生を作成し、" 移行ファイルは次のとおりです。

class CreateStudents < ActiveRecord::Migration 
def up 
create_table :students do |t| 
    t.string "name" 
    t.string "tracking_id" 
    t.float "matric_percentage" 
    t.integer "monthly_income" 
    t.column "SEX", 'CHAR(1)' 
    t.string "section" , index: true, foreign_key: true 
    t.string "city" 
    t.string "father_name" 
    t.string "DOB" 
    t.string "email" 
    t.string "phone_number" 
    t.string "secondary_phone_number" 
    t.string "mailing_address" 
    t.string "username" 
    t.string "password_digest" 
    t.timestamps null: false 
end 
end 
def down 
drop_table :students 
    end 
end 

マイモデルstudent.rbは、次のようになります。

:ここ

class Student < ActiveRecord::Base 
    belongs_to :sections 
has_secure_password 
def self.authenticate(user,pass) 
    student = Student.find_by_username(user) 
    if student.authenticate(pass) 
     return student[:id] 
    else 
     return false 
    end 
end 
end 

は私students_controller.rbは(のみ関連機能)であります

class StudentsController < ApplicationController 
    def new 
    @student = Student.new 
    end 
    def create 
    @student = Student.new(student_params) 
    @student.id=student_params[:tracking_id] 
    respond_to do |format| 
     if @student.save 
     flash[:notice] = 'Student was successfully created.' 
    format.html { redirect_to users_path(:admin => "students_view")} 
    format.json { render :show, status: :created, location: @student } 
    else 
    format.html { render :new } 
    format.json { render json: @student.errors, status: :unprocessable_entity } 
    end 
end 
def student_params 
    params.require(:student).permit(:name, :tracking_id, :matric_percentage, :monthly_income, :SEX, :section,:city, :father_name, :DOB, :email, :phone_number, :secondary_phone_number, :mailing_address, :username, :password) 
end 

私のフォームビューです:

 <%= bootstrap_form_for Student.new do |f| %> 
     <%= f.errors_on :name %> 
     <%= f.text_field :name, label: "Name", :required => true%> 
     <%= f.text_field :tracking_id, label: 'NOP Tracking ID', :required => true %> 
     <!--<%= f.text_field :section, label: "Section", :required => true %>--> 
     <%= f.select :section, [["Select:", "?"],["Section A", "A"], ["Section B", "B"],["Section C", "C"],["Section D", "D"],["Section E", "E"],["Section F", "F"],["Section G", "G"], ["Section H", "H"], ["Section I", "I"], ["Section J", "J"], ["Section K", "K"], ["Section L", "L"]], { label: "Section" },{ class: "selectpicker" } %> 
     <%= f.text_field :father_name, label: 'Father Name', :required => true %> 
     <%= f.text_field :DOB, label: 'Date of Birth', :required => true, help: "Be Careful! Enter date in dd/mm/yyyy pattern only" %> 
     <%= f.select :SEX,[["Select:", "?"],["Male", "M"], ["Female", "F"]],{ label: "Gender" },{ class: "selectpicker" } %> 
     <%= f.text_field :matric_percentage, label: "Matric Percentage", :required => true %> 
     <%= f.number_field :monthly_income, label: "Monthly income", :required => true %> 
     <%= f.text_field :city, label: 'City' %> 
     <%= f.email_field :email, label: 'Email Address' %> 
     <%= f.text_field :phone_number, label: 'Phone Number', :required => true %> 
     <%= f.text_field :secondary_phone_number, label: 'Secondary Phone Number', :required => true %> 
     <%= f.text_field :mailing_address, label: 'Mailing Address' %> 
     <%= f.text_field :username, label: 'Username', :required => true %> 
     <%= f.text_field :password, label: 'Password', :required => true %> 
     <div class="clearfix" type = "submit"> 
     <%= f.submit %> 
     <% end %> 

、完全なエラー声明:

Mysql2::Error: Duplicate entry '2016' for key 'PRIMARY': INSERT INTO `students` (`name`, `tracking_id`, `matric_percentage`, `monthly_income`, `SEX`, `section`, `city`, `father_name`, `DOB`, `email`, `phone_number`, `secondary_phone_number`, `mailing_address`, `username`, `password_digest`, `id`, `created_at`, `updated_at`) VALUES ('Sohail Aslam', '2016-N-7865', 344.0, 455, 'F', 'C', 'Lahore', 'Aslam', '25/12/1995', '[email protected]', '+923229499463', '+923229499463', 'Lahore', 'student', '$2a$10$SZAV08mASBTM8oQr1.P.IOIKRD.Acn/F/VfBDI0DS2.n4cVuWO9B2', 2016, '2016-04-07 18:54:50', '2016-04-07 18:54:50') 
+0

ビューを作成してコントローラ#createアクションコード – Sukanta

+0

を追加します。今見てもらえますか? –

+0

@ student.id = student_params [:tracking_id]の必要性は何ですか?あなたはすでにこれを初期化していますstudents_paramを渡して – Sukanta

答えて

1

問題はラインidtracking_idと同じではありません

@student.id=student_params[:tracking_id] 

です。 idはテーブルのプライマリキー(PK)ですが(マイグレーションによって自動的に追加されます) tracking_idは追加された追加キーです。

標準のPKを保持し、DBに値を設定させる必要があります(通常はシーケンスを使用します)。 ユーザがフォームに入力したトラッキングIDをidプロパティに割り当てるので、あなたはPKの世話をRailsに伝えます。これは文字列なので、整数に変換されます。あなたはintに「2016-1-1234」を変換するときに何が起こるかを参照してください:

puts "2016-1-1234".to_i # => 2016 

フォームを提出した後、今DBでPK 2016を持つ学生があります。また、次のユーザーには同じPK値が割り当てられます。したがって、DBは、すでに同じPKを持つ行が存在すると不平を言います。

あなたのコードのいくつかの発言:

  • 私はすべて小文字(DOB、SEX)カラム名を維持したいです。一貫性のために。
  • SEX列がt.stringで作成することができます
  • :秒、リミット:1
  • あなたのTRACKING_IDに一意のインデックスを追加する必要があります:ADD_INDEX(:学生、:TRACKING_ID、ユニーク:真)
  • おそらく、作成しました足場からのコントローラ? respond_to、format.json、format.htmlを削除すると、format.htmlブロックの内容は実際には十分です(JSON APIを使用しない限り)。
関連する問題