【问题标题】:Rails and Devise- How do I make the username migration unique and show an error if it is not?Rails 和 Devise - 如何使用户名迁移唯一并在不是时显示错误?
【发布时间】:2015-02-10 11:42:23
【问题描述】:

我正在为我的 rails 应用程序使用设计。我想添加用户名字段,所以我向数据库添加了迁移。 现在我想设计验证 user_name 字段的唯一性,但我无法弄清楚如何做到这一点。 我还希望它像使用默认电子邮件字段一样显示错误。

【问题讨论】:

    标签: ruby-on-rails ruby model devise rails-migrations


    【解决方案1】:

    只需在User 模型中为user_name 添加验证

    validates :user_name, uniqueness: true
    

    【讨论】:

      【解决方案2】:
      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-10-26
        • 1970-01-01
        • 2023-01-14
        • 2016-08-07
        • 1970-01-01
        相关资源
        最近更新 更多