Ruby-on-rails 向 Rails 应用程序中的设计视图/模型添加额外的字段和验证

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3692905/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 23:12:23  来源:igfitidea点击:

Adding additional field and validation to Devise view/model in Rails app

ruby-on-railsvalidationdevise

提问by jkvor

I generated the default deviseviews with:

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

rails generate devise:views

Then I added a usernamefield to the views/devise/registrations/new.html.erbform.

然后我usernameviews/devise/registrations/new.html.erb表单中添加了一个字段。

Currently, only emailand passwordvalidation occurs. How do I validate presence and uniqueness of the usernamefield? Do I need to add something to the Usermodel?

目前,只有emailpassword验证发生。如何验证该username字段的存在性和唯一性?我需要在User模型中添加一些东西吗?

回答by lashleigh

I used both the of the tutorials mentioned in the other answers, Railscast #210and 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.

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

If you added username with a simple migration -

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

rails generate migration addUsernameToUser username:string

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.

然后设计不会对该字段做任何特殊处理,因此您需要自己在 User 模型中添加验证和唯一性检查。

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

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

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

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.

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

回答by ecoologic

Rails 4 and Strong Parameters

Rails 4 和强参数

On top of the above I had to generate the views with:

在上述之上,我必须生成视图:

$ rails g devise:views

then in devise.rbadd:

然后devise.rb添加:

config.scoped_views = true

and finally configure the permitted parameters as below for sign_upas below:

最后配置允许的参数sign_up如下:

class ApplicationController < ActionController::Base

  before_filter :configure_permitted_parameters, if: :devise_controller?

  protected

    def configure_permitted_parameters
      devise_parameter_sanitizer.for(:sign_up) do |u|
        u.permit :username, :email, :password, :password_confirmation
      end
    end
end

This is described in Devise Doc

这在设计文档中描述

Also, my validation for usernameis the following:

另外,我的验证username如下:

validates :username, presence: true
validates :username, uniqueness: true, if: -> { self.username.present? }

I use two lines, so if usernameis blank I get only one error.

我使用两行,所以如果username是空白,我只会得到一个错误。

回答by Curtis M

If anybody is wondering how to get the login to check for username if its blank or to make sure to users cannot have the same username. I spent quite a few hours trying to figure this out and in the ned I only had to add :

如果有人想知道如何登录以检查用户名是否为空或确保用户不能使用相同的用户名。我花了好几个小时试图弄清楚这一点,在 ned 中我只需要添加:

validates_uniqueness_of :username, case_sensitive: false
validates_presence_of :username

to your user.rb file in app/models/

到 app/models/ 中的 user.rb 文件

Here are the docs... https://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

这是文档... https://api.rubyonrails.org/classes/ActiveRecord/Validations/ClassMethods.html

This now throws the errors I need. I feel like an idiot because I found uniquness_of first , then went back to and spent hours trying to figure out how to check for a blank field then found it is in the same documentation as the other...I am a noob.

这现在抛出我需要的错误。我觉得自己像个白痴,因为我首先找到了 uniquness_of ,然后回到并花了几个小时试图弄清楚如何检查空白字段然后发现它与另一个在同一个文档中......我是一个菜鸟。

Now onto figure out how to change the error messages since they are not in the devise.en.yml

现在弄清楚如何更改错误消息,因为它们不在 devise.en.yml 中

回答by julienXX

Just add a username field to your User model and on the Devise wiki: http://github.com/plataformatec/devise/wiki/Sign-in-using-login-or-mail

只需在您的用户模型和设计维基上添加一个用户名字段:http: //github.com/plataformatec/devise/wiki/Sign-in-using-login-or-mail

Hope it helps.

希望能帮助到你。