Rails错误消息:ActiveRecord :: NotNullViolation

时间:2017-09-29 03:20:42

标签: ruby-on-rails sqlite activerecord devise omniauth

您好我收到以下错误:
ActiveRecord::NotNullViolation
我已经检查了rails主页,看起来这个错误是在无法插入或更新记录时引起的,因为它会违反非空约束。
我的问题是如何绕过这个错误?理想情况下,我想存储用户会话数据,但我不知道如何解决这个问题。

注意:我使用的是DeviseOmni-Auth: Twitter

以下是schema.rb

ActiveRecord::Schema.define(version: 20170928215550) do
 create_table "users", force: :cascade do |t|
  t.string "email", default: "", null: false
  t.string "encrypted_password", default: "", null: false
  t.string "reset_password_token"
  t.datetime "reset_password_sent_at"
  t.datetime "remember_created_at"
  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"
  t.datetime "created_at", null: false
  t.datetime "updated_at", null: false
  t.string "provider"
  t.string "uid"
  t.index ["email"], name: "index_users_on_email", unique: true
  t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
 end
end

App > Models > user.rb

class User < ApplicationRecord
 # Include default devise modules. Others available are:
 # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers => [:twitter]
  # method to handle data response from twitter
  def self.from_omniauth(auth)
   where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
     user.provider = auth.provider
     user.uid = auth.uid
     user.email = auth.info.email
     user.password = Devise.friendly_token[0, 20]
   end
 end
end

App > Controllers > users > omniauth_callbacks_controller.rb

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def twitter
    @user = User.from_omniauth(request.env["omniauth.auth"])
    sign_in_and_redirect @user
    set_flash_message(:notice, :success, :kind => "Twitter")
  end
  def failure
    redirect_to 'home'
  end
end

以下是完整的错误消息:

SQLite3::ConstraintException: NOT NULL constraint failed: users.email: INSERT INTO "users" ("email", "encrypted_password", "sign_in_count", "current_sign_in_at", "last_sign_in_at", "current_sign_in_ip", "last_sign_in_ip", "created_at", "updated_at", "provider", "uid") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

Extracted source (around line #4):

 def twitter
    @user = User.from_omniauth(request.env["omniauth.auth"])
   LINE 4--> sign_in_and_redirect @user
   set_flash_message(:notice, :success, :kind => "Twitter")
 end
 def failure

1 个答案:

答案 0 :(得分:2)

我认为这个问题来自内部&#34; from_omniauth&#34;方法

Twitter不会通过API向您发送电子邮件

因此,当您使用来自&#34; auth.info.email&#34;的空电子邮件first_or_create用户时它会引发例外。

因为您的用户的电子邮件列是:

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

希望得到这个帮助,