在Rails应用程序中为Devise视图/模型添加其他字段和验证 [英] Adding additional field and validation to Devise view/model in Rails app

查看:75
本文介绍了在Rails应用程序中为Devise视图/模型添加其他字段和验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我生成了默认的设计视图:

rails generate devise:views

然后我添加了用户名字段到 views / devise / registrations / new.html.erb 表单。

Then I added a username field to the views/devise/registrations/new.html.erb form.

目前,只有电子邮件密码验证。如何验证用户名字段的存在和唯一性?我需要向用户模型添加东西吗?

Currently, only email and password validation occurs. How do I validate presence and uniqueness of the username field? Do I need to add something to the User model?

推荐答案

使用其他答案中提到的教程, Railscast#210 Devise Wiki 。但是,据我所知,他们没有明确说明如何验证用户名字段的存在和/或唯一性。

I used both the of the tutorials mentioned in the other answers, Railscast #210 and the Devise Wiki. However, so far as I could tell they do not explicitly say how to validate the presence and/or uniqueness of the username field.

如果您添加了简单迁移的用户名 -

If you added username with a simple migration -

rails generate migration addUsernameToUser username:string

然后,devise不会对该字段做任何特殊的操作,所以你需要在用户模型中自行添加验证和唯一性检查。

Then devise doesn't do anything special with that field, so you need to add checks for validation and uniqueness yourself in the User model.

class User < ActiveRecord::Base
...
  validates_presence_of :username
  validates_uniqueness_of :username

但是,如果您查看RailsCast#209,则有一个用于创建用户模型的迁移示例。

However, If you look at the RailsCast #209 there is an example of the migration used to create the User model.

class DeviseCreateUsers < ActiveRecord::Migration  
  def self.up  
    create_table(:users) do |t|  
      t.database_authenticatable :null => false  
      # t.confirmable  
      t.recoverable  
      t.rememberable  
      t.trackable  
      # t.lockable :lock_strategy => :failed_attempts, :unlock_strategy => :both  

      t.timestamps  
    end  

    add_index :users, :email,                :unique => true  
    # add_index :users, :confirmation_token,   :unique => true  
    add_index :users, :reset_password_token, :unique => true  
    # add_index :users, :unlock_token,         :unique => true  
  end  

  def self.down  
    drop_table :users  
  end  
end  

请注意,用户电子邮件被定义为唯一的。也许如果使用相同的语法添加用户名,那么设计魔法将会照顾到存在和唯一性。

Notice here that the users email is defined as being unique. Perhaps if username was added using this same syntax then devise magic would take care of presence and uniqueness.

这篇关于在Rails应用程序中为Devise视图/模型添加其他字段和验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆