为什么Devise不能注册新用户?

时间:2016-04-16 05:28:16

标签: ruby-on-rails ruby json ajax devise

错误消息:

Processing by RegistrationsController#create as */*
  Parameters: {"user"=>{"email"=>"happytimes@gmail.com", "password"=>"[FILTERED]"}}
   (0.1ms)  begin transaction
  User Exists (0.1ms)  SELECT  1 AS one FROM "users" WHERE "users"."email" = 'happytimes@gmail.com' LIMIT 1
   (0.0ms)  rollback transaction
Completed 422 Unprocessable Entity in 73ms (Views: 0.1ms | ActiveRecord: 0.8ms)

代码:

JavaScript拨打电话:

    register = function (username, password) {
        $.ajax({ url: '/users'
               , method: 'POST'
               , headers: { 'X-Transaction': 'POST Example'
                          , 'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
                          }
               , data: { user: { email: username
                               , password: password
                               }
                       }
               });
    },

控制器:

class RegistrationsController < Devise::RegistrationsController
  clear_respond_to
  respond_to :json

  def create
    user_params = devise_parameter_sanitizer.params.require(:user)
    user_params.require(:email)
    user_params.require(:password)
    devise_parameter_sanitizer.params[:user] = user_params.permit(:email, :password)
    super
  end
end

型号:

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # validates_confirmation_of :password
end

代码在完成我的RegistrationController #create自定义逻辑并进入super调用后失败,最终以Devise创建方法结束。

    16: def create
    17:   build_resource(sign_up_params)
    18: 
    19:   resource_saved = resource.save
 => 20:   yield resource if block_given?
    21:   if resource_saved
    22:     if resource.active_for_authentication?
    23:       set_flash_message :notice, :signed_up if is_flashing_format?
    24:       sign_up(resource_name, resource)
    25:       respond_with resource, location: after_sign_up_path_for(resource)
    26:     else
    27:       set_flash_message :notice, :"signed_up_but_#{resource.inactive_message}" if is_flashing_format?
    28:       expire_data_after_sign_in!
    29:       respond_with resource, location: after_inactive_sign_up_path_for(resource)
    30:     end
    31:   else
    32:     clean_up_passwords resource
    33:     @validatable = devise_mapping.validatable?
    34:     if @validatable
    35:       @minimum_password_length = resource_class.password_length.min
    36:     end
    37:     respond_with resource
    38:   end
    39: end

[2] pry(#<RegistrationsController>)> resource_saved
=> false

相关的Gemfile依赖项:

source 'https://rubygems.org'

ruby '2.2.2'

gem 'rails', '4.2.0'
...

# Authentication manager
gem 'devise', '~> 3.4.1

0 个答案:

没有答案