Как я могу исправить ошибку SQLite3 :: ConstraintException: НЕ NULL с устройством в рельсах? - PullRequest
0 голосов
/ 30 сентября 2018

Я внедряю систему аутентификации с устройством devise в рельсах, но при регистрации пользователя, в данном случае учащегося, пропускается следующая ошибка:

ActiveRecord::NotNullViolation in Devise::RegistrationsController#create

SQLite3::ConstraintException: NOT NULL constraint failed: students.codigo: INSERT INTO "students" ("email", "encrypted_password", "created_at", "updated_at") VALUES (?, ?, ?, ?)

Я исправляю эту ошибку весь день,но ничего, что я могу решить.Я реализовал before_action в контроллере Students_controller:

class StudentsController < ApplicationController
  before_action :configure_devise_params, if: :devise_controller?

  def configure_devise_params
    devise_parameter_sanitizer.permit(:sign_up) do |user|
      user.permit(:codigo, :documento, :nombres, :apellidos, :es_egresado, :email, :password, :password_confirmation)
    end
  end
  ...
end

, но проблема все еще не решена.Та же самая ошибка происходит, когда я удаляю devise, удаляю из него все ссылки, а также внедряю сильные параметры в контроллере, без этого реестр работает удовлетворительно.Но с сильными параметрами и devise не работает, он передает данные в null в команде SQL.

База данных ученика выглядит следующим образом:

create_table "students", id: false, force: :cascade do |t|
    t.integer "codigo", null: false
    t.integer "documento", null: false
    t.string "nombres", null: false
    t.string "apellidos", null: false
    t.integer "es_egresado", null: false
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.decimal "promedio_carrera"
    t.string "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["documento"], name: "index_students_on_documento", unique: true
    t.index ["email"], name: "index_students_on_email", unique: true
    t.index ["reset_password_token"], name: "index_students_on_reset_password_token", unique: true
  end

И ее реализация переносится следующим образом:

class DeviseCreateStudents < ActiveRecord::Migration[5.1]
  def change
    create_table :students, {
      :id => false,
      :primary_key => :codigo
    } do |t|
      ## Database authenticatable
      t.integer :codigo, null: false
      t.integer :documento, null: false
      t.string :nombres, null: false
      t.string :apellidos, null: false
      t.integer :es_egresado, null: false

      t.string :email,              null: false, default: ""
      t.string :encrypted_password, null: false, default: ""

      t.decimal :promedio_carrera, null: true

      ## Recoverable
      t.string   :reset_password_token
      t.datetime :reset_password_sent_at

      ## Rememberable
      t.datetime :remember_created_at

      ## Trackable
      # t.integer  :sign_in_count, default: 0, null: false
      # t.datetime :current_sign_in_at
      # t.datetime :last_sign_in_at
      # t.string   :current_sign_in_ip
      # t.string   :last_sign_in_ip

      ## Confirmable
      # t.string   :confirmation_token
      # t.datetime :confirmed_at
      # t.datetime :confirmation_sent_at
      # t.string   :unconfirmed_email # Only if using reconfirmable

      ## Lockable
      # t.integer  :failed_attempts, default: 0, null: false # Only if lock strategy is :failed_attempts
      # t.string   :unlock_token # Only if unlock strategy is :email or :both
      # t.datetime :locked_at


      t.timestamps null: false
    end

    add_index :students, :email,                unique: true
    add_index :students, :reset_password_token, unique: true
    add_index :students, :documento, unique: true
    # add_index :students, :confirmation_token,   unique: true
    # add_index :students, :unlock_token,         unique: true
  end
end

Параметры:

{"utf8"=>"✓",
 "authenticity_token"=>"6zdENP1iREYYM+qpqtskqRJ+aB38NIX/nG9jFsoGlImqUVyS9bsmBF6Uc7xvDD/J50/zamlZbbm2rwAaCgOmuw==",
 "student"=>
  {"codigo"=>"625762",
   "documento"=>"107526792",
   "nombres"=>"Carlos",
   "apellidos"=>"Garnica",
   "es_egresado"=>"0",
   "email"=>"wcarlosfg.1234567890@hotmail.com",
   "password"=>"[FILTERED]",
   "password_confirmation"=>"[FILTERED]"},
 "commit"=>"Registrar"}

Я также уточняю, что когда я создаю другую таблицу Student, удаляю предыдущую и удаляю для полей параметр null, ошибка непоявляются, но поля, которые якобы были сохранены, остаются в базе данных NULL

ОБНОВЛЕНИЕ: Измените базу данных, сделав все поля пустыми, и форма отправит пустые поля, независимо от того, имеют ли они данные вформа или нет, это очень редко.При проверке объекта он показывает следующее:

irb(main):002:0> Student.last
  Student Load (0.0ms)  SELECT  "students".* FROM "students" ORDER BY "students"."id" DESC LIMIT ?  [["LIMIT", 1]]
=> #<Student id: 2, codigo: nil, documento: nil, nombres: nil, apellidos: nil, es_egresado: nil, promedio_carrera: nil, email: "wcarlosfg.1234567890@hotmail.com", created_at: "2018-09-30 07:46:39", updated_at: "2018-09-30 07:46:39">

РЕШЕНИЕ: После дня, когда мы изучали ошибку, единственным решением было перезаписать драйвер устройства для записей спосле этого я смог добавить логику и внедрить сильные параметры для правильной работы реестра.

...