Mysql2 ::错误:使用Rails复制键'PRIMARY'的条目'2016'

时间:2016-04-07 17:46:43

标签: mysql ruby-on-rails ruby

我在这个论坛上几乎尝试了所有答案,但没有任何帮助。

我的所有学生都有以这种格式的跟踪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', '17100283@lums.edu.pk', '+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')

1 个答案:

答案 0 :(得分:2)

问题就在这一行

@student.id=student_params[:tracking_id]

idtracking_id不同。虽然id是您的表的主键(PK)(通过迁移自动添加),但 tracking_id是您添加的附加键。

您应该保留标准PK并让DB设置其值(通常通过序列完成)。 由于您将用户在表单中输入的跟踪ID分配给id属性,因此您告诉Rails您要处理PK。因为它是一个String,所以它被转换为整数。看看将“2016-1-1234”转换为int:

时会发生什么
puts "2016-1-1234".to_i # => 2016

现在,一旦您提交了表格,就会有一名学生在数据库中使用PK 2016。并且还为下一个用户分配了相同的PK值。因此,DB会抱怨,已经有一行具有相同的PK。

对您的代码的一些评论:

  • 我会将列名全部保持为小写(DOB,SEX)。只是为了保持一致。
  • 可以使用t.string:sec,limit:1
  • 创建SEX列
  • 您应该为tracking_id添加唯一索引:add_index(:students,:tracking_id,unique:true)
  • 您可能已经从脚手架创建了控制器?删除respond_to,format.json以及format.html,format.html块的内容实际上已足够(除非你有一个JSON API)