我是Rails的新手,我建立了一个图书共享平台,并且想从电子邮件名称中设置用户名。并验证用户名必须至少5个字符,最多50个字符。我进行了设置,但验证不起作用。错误出现在屏幕上,但用户仍然可以注册。我使用Devise for User模型以及Devise Wiki。
user.rb
class User < ApplicationRecord
before_create :set_username
validates :email, presence: true
has_many :books
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :validatable
attr_accessor :login
def login
@login || self.username || self.email
end
private
def set_username
self.username = self.email.split('@').first
validates_length_of :username,
:minimum => 5, :maximum => 50,
presence: true,
uniqueness: true
end
def self.find_for_database_authentication(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
where(conditions).first
end
end
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
if conditions[:username].nil?
where(conditions).first
else
where(username: conditions[:username]).first
end
end
end
end
routes.rb
Rails.application.routes.draw do
devise_for :users, :path_prefix => 'd'
resources :dashboard
resources :books do
resources :comments
end
resources :users
match '/users/:id', to: 'users#show', via: 'get'
root 'welcome#index'
get 'dashboard/index'
get 'users/index'
end
devise / registiration / 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" %>
您可以通过将以下内容添加到来将电子邮件地址的第一部分用作用户名user.rb
:
def username
email.split(/@/).first
end
这样,对于用户来说,[email protected]
当您打电话user.username
或收到电子邮件时,current_user.username
您会得到alex
。
您不需要username
在数据库中添加列,也不需要在数据库中添加验证。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句