【发布时间】:2015-02-10 11:42:23
【问题描述】:
我正在为我的 rails 应用程序使用设计。我想添加用户名字段,所以我向数据库添加了迁移。 现在我想设计验证 user_name 字段的唯一性,但我无法弄清楚如何做到这一点。 我还希望它像使用默认电子邮件字段一样显示错误。
【问题讨论】:
标签: ruby-on-rails ruby model devise rails-migrations
我正在为我的 rails 应用程序使用设计。我想添加用户名字段,所以我向数据库添加了迁移。 现在我想设计验证 user_name 字段的唯一性,但我无法弄清楚如何做到这一点。 我还希望它像使用默认电子邮件字段一样显示错误。
【问题讨论】:
标签: ruby-on-rails ruby model devise rails-migrations
只需在User 模型中为user_name 添加验证
validates :user_name, uniqueness: true
【讨论】:
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_action :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:username, :email, :password, :password_confirmation, :remember_me) }
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 :username , uniqueness: {case_sesitive: false}
end
【讨论】: