-3.新装gem后要重启服务器
-2.开发数据库:
- bundle exec rake db:migrate
测试数据库:
- $ bundle exec rake db:test:prepare
-1. 创建对象:rails console
0.
- $ bundle exec annotate --position before
1.Active Record 提供了一系列的方法,直接用于创建、保存、查询数据对象,而无需使用关系数据库所用的结构化查询语言(structured query language, SQL)
2.生成用户模型
- rails generate model User name:string email:string
3. 和控制器的命令习惯不同,模型的名字是单数:控制器是 Users,而模型是 User
4.timestamps
是个特殊的方法,它会自动创建两个列,created_at
和 updated_at
,这两个列分别记录创建用户的时间戳和更新用户数据的时间戳。
5.用rake
命令来执行迁移
- $ bundle exec rake db:migrate
反迁移
- $ bundle exec rake db:rollback
6.模型注解
- $ bundle exec annotate --position before
7.用户数据验证
- class User < ActiveRecord::Base
- attr_accessible :name, :email
- validates :name, presence: true, length: { maximum: 50 }
- VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
- validates :email, presence: true, format: { with: VALID_EMAIL_REGEX }
- end
在数据库层也加上唯一性限制
在数据库中为 email
列建立索引,然后为索引加上唯一性限制。
- $ rails generate migration add_index_to_users_email #<span style="color: rgb(34, 34, 34); font-family: 'Helvetica Neue', 'Luxi Sans', 'DejaVu Sans', Tahoma, 'Hiragino Sans GB', 'Microsoft Yahei', STHeiti; font-size: 14.399999618530273px; line-height: 17.600000381469727px; background-color: rgba(255, 255, 255, 0.701961);">使用</span><code style="font-family: monospace, serif; font-size: 14.399999618530273px; color: rgb(34, 34, 34); line-height: 17.600000381469727px; background-color: rgba(255, 255, 255, 0.701961);">migration</code><span style="color: rgb(34, 34, 34); font-family: 'Helvetica Neue', 'Luxi Sans', 'DejaVu Sans', Tahoma, 'Hiragino Sans GB', 'Microsoft Yahei', STHeiti; font-size: 14.399999618530273px; line-height: 17.600000381469727px; background-color: rgba(255, 255, 255, 0.701961);"> 命令直接创建迁移文件</span>
- 保 Email 唯一性的迁移文件
- class AddIndexToUsersEmail < ActiveRecord::Migration
- def change
- add_index :users, :email, unique: true
- end
- end
- 执行数据库迁移操作
- $ bundle exec rake db:migrate