Rails - 设计错误:"电子邮件不能为空,密码不能为空白"在创建新用户时

时间:2014-10-29 11:02:30

标签: ruby-on-rails devise

我收到了之前已经回答过的错误,但没有一个答案对我有用,而且我完全难过了。

我正在使用设计,但它不可注册。

当我尝试创建新用户时,我收到错误“电子邮件不能为空,密码不能为空”。它们肯定不是空白,如日志中所示。参数哈希工作正常。该交易立即回滚。在控制台中创建新用户时,我不会遇到此问题。

编辑现有用户时效果很好。

解决了强大的参数问题设计问题。

提前致谢,我感谢您的帮助!

我的代码如下。

日志:

    Started POST "/users" for 127.0.0.1 at 2014-10-29 10:37:33 +0000
Processing by UsersController#create as HTML
  Parameters: {"utf8"=>"V", "authenticity_token"=>"8U+XxLIrE7MjOphsuorOwarggyZsj
3qTNQeap273QTo=", "user"=>{"name"=>"John Smith", "role"=>"MG", "client"=>""
, "email"=>"john@johnsmith.com", "password"=>"[FILTERED]", "passw
ord_confirmation"=>"[FILTERED]"}, "commit"=>"Sign up"}
   (0.0ms)  begin transaction
   (1.0ms)  rollback transaction
  Rendered users/new.html.erb within layouts/application (6.0ms)
  User Load (0.0ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORD
ER BY "users"."id" ASC LIMIT 1
  Rendered layouts/_header.html.erb (4.1ms)
#<ActiveModel::Errors:0x422fc88 @base=#<User id: nil, email: "", encrypted_passw
ord: "", reset_password_token: nil, reset_password_sent_at: nil, remember_create
d_at: nil, sign_in_count: 0, current_sign_in_at: nil, last_sign_in_at: nil, curr
ent_sign_in_ip: nil, last_sign_in_ip: nil, created_at: nil, updated_at: nil, nam
e: nil, client: nil, role: nil>, @messages={:email=>["can't be blank"], :passwor
d=>["can't be blank"], :name=>[], :role=>[], :client=>[], :password_confirmation
=>[]}>
Completed 422 Unprocessable Entity in 238ms (Views: 231.3ms | ActiveRecord: 1.0m
s)

应用程序控制器:

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
 protect_from_forgery with: :exception

 before_filter :configure_permitted_parameters, if: :devise_controller?

 def after_sign_in_path_for(user)
    projects_path
 end

 protected

 def configure_permitted_parameters
    devise_parameter_sanitizer.for(:account_update) << :name
    devise_parameter_sanitizer.for(:account_update) << :client
    devise_parameter_sanitizer.for(:sign_up) << [:name, :role, :client]
 end
end

新用户表格:

<%= form_for(@user) do |f| %>
   <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user.errors.count, "error") %> stopped this user from being created:</h2>

      <ul>
      <% @user.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div><%= f.label :name %><br />
    <%= f.text_field :name %></div>

  <div><%= f.label :role %><br />
  <%= select :user, :role, options_for_select(@role) %></div>

<div id="client_input"><%= f.label :client %><br />
    <%= f.text_field :client %></div>


  <div><%= f.label :email %><br />
  <%= f.email_field :email %></div>

  <div><%= f.label :password %> <% if @validatable %><i>(<%= @minimum_password_length %> characters minimum)</i><% end %><br />
    <%= f.password_field :password, autocomplete: "off" %></div>

  <div><%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "off" %></div>


  <div><%= f.submit "Sign up" %></div>
<% end %>

用户控制器:

class UsersController < ApplicationController
    before_filter :get_user, :only => [:index,:new,:edit]
  before_filter :client_restriction, only: [:index, :show, :new]


  def index
    @users = User.all
    respond_to do |format|
      format.json { render :json => @users }
      format.xml  { render :xml => @users }
      format.html
    end
  end

  def new
    @user = User.new
    @role = ["MG", "Client"]
  end

  def show
  @user = User.all
    @projects = Project.all      
  end


  def edit
    @user = User.find(params[:id])
    @role = ["MG", "Client"]
    end

   def update
    @user = User.find(params[:id])
    @role = ["MG", "Client"]
    @user.client == :client
    @user.role == :role

    if params[:user][:password].blank?
      [:password, :password_confirmation, :current_password].collect{|p| params[:user].delete(p)}
    else
      @user.errors[:base] << "The password you entered is incorrect." unless @user.valid_password?(params[:user][:current_password])
    end 
    respond_to do |format|
      if @user.update(user_params)
        sign_in(@user, :bypass => true) # To counter weird Devise error which logs users out after password change
        format.html { redirect_to projects_path, notice: 'Your account details were updated successfully' }
      else
        format.html { render :edit }
      end
    end
  end

  def destroy
    @user = User.find(params[:id])
    @user.destroy

    respond_to do |format|
      format.html { redirect_to root_path, notice: "Your account has been deleted. Sorry to see you go!" }      
    end
    end

  def create
    @role = ["MG", "Client"]
    @user = User.new
    if @user.save
      respond_to do |format|
        format.html { redirect_to :back, notice: "New user successfully created" }
      end
    else
      respond_to do |format|
        format.json { render :text => "Could not create user", :status => :unprocessable_entity } # placeholder
        format.xml  { head :ok }
        format.html { render :action => :new, :status => :unprocessable_entity }
      end
    end
    Rails.logger.info(@user.errors.inspect)
    end 


  def add_user
  end

    private 

  def get_user
    @current_user = current_user
  end
  def client_restriction
    redirect_to root_path, notice: "You are not authorised to create users" if current_user.role != "MG"
  end  
  def user_params
      params.require(:user).permit(:role, :name, :client, :email, :password, :password_confirmation, :authenticity_token, project: [:name, :client, :phase], section: [:title, :position, :project_id], deliverable: [:file, :preview, :title, :project_id, :section_id], link: [:hyperlink, :title, :project_id, :section_id], embed: [:section_id, :embed_link, :title, :project_id])
    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

  has_many :members
  has_and_belongs_to_many :projects
  has_many :sections    
  has_many :deliverables
  has_many :embeds
  has_many :links   

  accepts_nested_attributes_for :projects

end

2 个答案:

答案 0 :(得分:3)

您正在尝试创建空白User。尝试:

def create
  # ...
  @user = User.new user_params
  # ...
end

答案 1 :(得分:1)

试试这个我希望它为你工作

def configure_permitted_parameters
    devise_parameter_sanitizer.for(:account_update) << :name
    devise_parameter_sanitizer.for(:account_update) << :client
    devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:email, :password,:password_confirmation, :name, :role, :client) }
end