rails tutorials: data model

生成 User Model

1
rails g model User name:string email:string

验证

app/models/user.rb

存在性验证

1
2
3
class User < ApplicationRecord 
validates :name, presence: true
end

长度验证

1
2
3
4
class User < ApplicationRecord
validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true, length: { maximum: 255 }
end

电子邮件格式验证

1
2
3
4
5
6
class User < ApplicationRecord
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true, length: { maximum: 255 },
format: {with: VALID_EMAIL_REGEX}
end

唯一性验证

1
2
3
4
5
6
7
class User < ApplicationRecord
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :name, presence: true, length: { maximum: 50 }
validates :email, presence: true, length: { maximum: 255 },
format: {with: VALID_EMAIL_REGEX},
uniqueness: true
end

数据库层唯一性验证

rails generate migration add_index_to_users_email

1
2
3
4
5
class AddIndexToUsersEmail < ActiveRecord::Migration[6.0] 
def change
add_index :users, :email, unique: true
end
end
1
rails db:migrate

回调

保证存储在数据库中的电子邮件都是小写字母的形式

1
2
3
4
5
6
7
class User < ApplicationRecord
before_save { self.email = email.downcase }
validates :name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX }, uniqueness: true
end

添加安全密码

1
2
3
4
class User < ApplicationRecord
......
has_secure_password
end

在模型中调用这个方法后,会自动添加如下功能:

  1. 在数据库中的password_digest列存储安全的密码哈希值;
  2. 获得一对虚拟属性,20password和password_confirmation,而且创建用户对象时会执行存在性验证和 匹配验证;
  3. 获得authenticate方法,如果密码正确,返回对应的用户对象,否则返回false。

has_secure_password 发挥功效的唯一要求是,对应的模型中有个名为 password_digest 的属性。因此,创建一个适当的迁移文件,添加 password_digest 列。

1
rails generate migration add_password_digest_to_users password_digest:string
1
2
3
4
5
class AddPasswordDigestToUsers < ActiveRecord::Migration[6.0] 
def change
add_column :users, :password_digest, :string
end
end
1
rails db:migrate

has_secure_password 方法使用先进的 bcrypt 哈希算法计算密码摘要。使用 bcrypt 计算密码哈希值,就算攻击者设法获得了数据库副本也无法登录网站。我们要把 bcrypt gem 添加到 Gemfile 文件中。

Donate article here