ActiveRecord(一)

ActiveRecord(一)

命名和模式约定

命名约定


模式约定


不使用约定


指定表名
1
self.table_name

指定主键

1
self.primary_key

基本操作

创建


1
2
3
4
User.create(:name => 'xiaowang', :email => 'xiaowang@gmail.com')

@user = User.new(:name => 'xiaowang', :email => 'xiaowang@gmail.com')
@user.save

读取


1
2
3
4
5
User.all

User.find #(主键)

User.find_by(:name => 'xiaowang') #第一个符合条件的

更新


1
2
3
@user.update(:name => 'xiaowang', :email => 'xiaowang@gmail.com')

User.update_all(:name => 'nima')

删除


删除一个数据
1
@user.destroy

删除表中所有数据

1
User.destroy_all

数据迁移

迁移

1
rake db:migrate

回滚

1
rake db:rollback

1
rake db:rollback STEP=2

单独创建迁移

Creatxxx


1
rails g migration CreateWallets

AddxxxToyyy


1
rails g migration AddLocationToUser location:string

RemovexxxFromyyy


1
rails g migration RemoveLocationFromUser location:string

change方法

table

create_table

rename_table

drop_table

join_table

create_join_table

drop_join_table

column

add_column

rename_column

remove_column

index

add_index

rename_index

remove_index

reference

add_reference

remove_reference

timestamps

add_timestamps

remove_timestamps

up和down方法

revert方法


1
2
3
4
5
6
7
require_relative "20161202100202_create_uesrs"

class RevertCreateUsers < ActiveRecord::Migration
def change
revert CreateUsers
end
end

种子数据


db/seed.rb
1
2
3
4
5
15.times do |n|
User.create(:name => 'male_user_#{n}', :phone_number => '13012312311', :gender => 'male' )
User.create(:name => 'female_user_#{n}', :phone_number => '13012312311', :gender => 'female' )

end

搭建数据库

1
rake db:setup

填充种子数据

1
rake db:seed

重建数据库

1
rake db:reset

设置环境

1
RAILS_ENV=test

导出数据库

1
rake db:schema:load

数据验证

跳过数据验证


1
@user.save(validate:false)

是否合法


valid?
1
@user.valid?

invalid?

1
@user.invalid?

错误信息


1
@user.errors.messages

1
@user.errors[:name]

presence


不为空
1
2
3
4
5
class User < ApplicationRecord

validates :name, presence: true

end

absence


为空
1
validates :name, absence: true

length


长度

  • minimum
  • maximum
  • in
  • is
    1
    2
    3
    validates :name, length: {maximum: 3}
    validates :name, length: {in: 3..20}
    validates :name, length: {is: 6}

confirmation


确认
1
validates :password, confirmation: true

inclusion/exclusion


范围
1
2
validates :province, inclusion: {in: ['北京', '上海']}
validates :age, exclusion: {in: 0..18}

format


格式
1
validates :phone_number, format: {with: /1[0-9]{10}\z/ }

uniqueness


唯一
1
validates :name, uniqueness: true

不区分大小写

1
validates :name, uniqueness: {case_sensitive: false}

常用验证选项

  • allow_nil
  • allow_blank
  • message
  • on
    1
    2
    3
    4
    5
    6
    validates :password, confirmation: true
    validates :password, :password_confirmation, presence: {on: :create, message: '密码和确认密码不能为空'}
    validates :password, length: {minimum: 6}


    validates :name, uniqueness: {allow_nil: true}

条件验证


指定symbol
1
2
3
4
5
validates :name, uniqueness: true, :if => :test?

def test?
false
end

指定字符串

1
validates :phone_number, uniqueness: true, :if => 'name.nil'

指定proc

1
validates :phone_number, uniqueness: true, :if => Proc.new {name.nil?}

1
2
3
4
5
6
7
8
9
with_options if: :test? do
validates :name, uniqueness: true
validates :name, uniqueness: true

end

def test?
(1+1 == 2)
end

联合条件

1
2
3
4
5
6
7
8
9
10
11
12
13
with_options if: :test?, unless: :test2? do
validates :name, uniqueness: true
validates :name, uniqueness: true

end

def test?
(1+1 == 2)
end

def test2?
(1+1 == 2)
end

自定义验证方法

  • validates_with
  • validates_each
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    class MyValidator < ActiveModel::Validator

    def validate(record)
    if record.name.nil?
    record.errors[:name] << '用户名不能为空'
    end
    if record.phone_number.nil?
    record.errors[:phone_number] << '手机号码不能为空'
    end

    end
    end


    class User < ApplicationRecord

    validates_with MyValidator

    end
1
2
3
4
5
6
7
8
9
10
11
class User < ApplicationRecord

validate :my_validator

def my_validator
if name.nil?
errors[:name] << '用户名不能为空'
end
end

end

验证错误

  • errors
  • errors[:attribute]
  • errors.add
  • errors.size
文章目录
  1. 1. 命名和模式约定
    1. 1.0.1. 命名约定
    2. 1.0.2. 模式约定
    3. 1.0.3. 不使用约定
  • 2. 基本操作
    1. 2.0.1. 创建
    2. 2.0.2. 读取
    3. 2.0.3. 更新
    4. 2.0.4. 删除
  • 3. 数据迁移
    1. 3.1. 单独创建迁移
      1. 3.1.1. Creatxxx
      2. 3.1.2. AddxxxToyyy
      3. 3.1.3. RemovexxxFromyyy
    2. 3.2. change方法
      1. 3.2.1. table
        1. 3.2.1.1. create_table
        2. 3.2.1.2. rename_table
        3. 3.2.1.3. drop_table
      2. 3.2.2. join_table
        1. 3.2.2.1. create_join_table
        2. 3.2.2.2. drop_join_table
      3. 3.2.3. column
        1. 3.2.3.1. add_column
        2. 3.2.3.2. rename_column
        3. 3.2.3.3. remove_column
      4. 3.2.4. index
        1. 3.2.4.1. add_index
        2. 3.2.4.2. rename_index
        3. 3.2.4.3. remove_index
      5. 3.2.5. reference
        1. 3.2.5.1. add_reference
        2. 3.2.5.2. remove_reference
      6. 3.2.6. timestamps
        1. 3.2.6.1. add_timestamps
        2. 3.2.6.2. remove_timestamps
    3. 3.3. up和down方法
    4. 3.4. revert方法
    5. 3.5. 种子数据
    6. 3.6. 数据验证
      1. 3.6.1. 跳过数据验证
      2. 3.6.2. 是否合法
      3. 3.6.3. 错误信息
      4. 3.6.4. presence
      5. 3.6.5. absence
      6. 3.6.6. length
      7. 3.6.7. confirmation
      8. 3.6.8. inclusion/exclusion
      9. 3.6.9. format
      10. 3.6.10. uniqueness
      11. 3.6.11. 常用验证选项
      12. 3.6.12. 条件验证
      13. 3.6.13. 自定义验证方法
      14. 3.6.14. 验证错误
  • |