我正在尝试为我的网站创建用户,在注册网站时,我希望用户信息进入我的后台。我安装了 gem Devise 和 gem CanCanCan,但是当我尝试在注册页面中注册时,它一直说 2 个错误禁止保存此用户:电子邮件不能为空,电子邮件不能为空。我检查了类似的问题,但无法纠正我的问题。
我在轨道上的红宝石 obv
这是我的迁移:
# frozen_string_literal: true
class DeviseCreateUsers < ActiveRecord::Migration[5.2]
def change
create_table :users do |t|
## Database authenticatable
t.string :email
t.string :encrypted_password
t.string :token
## Recoverable
t.string :reset_password_token
t.datetime :reset_password_sent_at
## Rememberable
## 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
end
add_index :users, :email, unique: true
add_index :users, :reset_password_token, unique: true
# add_index :users, :unlock_token, unique: true
end
end
这是我的用户.rb:
class User < ApplicationRecord
has_secure_password
validates_presence_of :email
validates_uniqueness_of :email
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
end
这是我的users_controller.rb:
class UsersController < ApplicationController
def user_params
params.require(:user).permit(:email, :password, :password_confirmation, :role)
end
end
注册 new.html.erb:
<h2>Sign up</h2>
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= render "devise/shared/error_messages", resource: resource %>
<div class="field">
<%= f.label :email %><br />
<%= f.email_field :email, autofocus: true, autocomplete: "email" %>
</div>
<div class="field">
<%= f.label :password %>
<% if @minimum_password_length %>
<em>(<%= @minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "new-password" %>
</div>
<div class="field">
<%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation, autocomplete: "new-password" %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
<%= render "devise/shared/links" %>
告诉我我是否错过了任何东西,但我不认为所以我是 rails 的新手,所以我可能是 谢谢
has_secure_password
用于自定义身份验证,不是必需的/不应与Devise一起使用。
删除User
模型中的UsersController
和email
验证。Devise 为您处理所有这些。
如果您想在注册时将 Devise 不考虑的其他属性列入白名单(在您的情况下它只是role
(,然后将以下内容添加到您的ApplicationController
中......
before_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.permit(:sign_up, keys: [:role])
end
对于像 Devise 这样维护良好且经过实战考验的宝石,阅读文档而不是偏离它非常重要,除非您有充分的理由这样做。