rails中sql的增删改(数据迁移)

rails中sql的增删改(数据迁移)

https://guides.ruby-china.org/active_record_migrations.html

Rails 迁移(migration)强大功能

  • Rails 支持迁移(migration)功能,允许我们使用纯 Ruby 代码定义数据结构,而不用学习 SQL 数据定义语言。

  • Rails 提供了一套用于运行迁移的 bin/rails 任务。其中最常用的是 rails db:migrate 任务,用于调用所有未运行的迁移中的 change 或 up 方法。

#rails db:migrate 命令调用change方法,再执行create_table方法, 
#而create_table方法通过 t 对象在数据库中创建 name 和 email 两个列
class CreateUsers < ActiveRecord::Migration[5.0] 
    def change
        create_table :users do |t|
            t.string :name
            t.string :email
            t.timestamps 
        end
    end 
end

ActiveRecord

  1. 每一个数据库表对应创建一个类.类的每一个对象实例对应于数据库中表的一行记录; 通常表的每个字段在类中都有相应的Field;
  2. ActiveRecord同时负责把自己持久化. 在ActiveRecord中封装了对数据库的访问, 即CRUD;
  3. ActiveRecord是一种领域模型(Domain Model), 封装了部分业务逻辑;

命名约定

  • 数据表名:复数,下划线分隔单词(例如 book_clubs)
  • 模型类名:单数,每个单词的首字母大写(例如 BookClub)
数据表名(Schema)模型类名
postsPost
book_clubsBookClub

创建数据表

 def change
   create_table :vip_logs do |t|
     t.integer :shop_id
     t.integer :branch_id
     t.string :type
     t.integer :operator_id
     t.string :operator_name
     t.datetime :created_at
     t.datetime :updated_at
    end
  end

添加字段

def change
    add_column :products, :part_number, :string
    add_column :products, :price, :decimal
end

//products为数据表名,part_number为字段,string为字段类型

删除字段

def change
   remove_column :products, :part_number, :string
end

deleted_at :datetime 软删除


REST 架构

REST软件架构使用了CRUD原则,该原则告诉我们对于资源(包括网络资源)只需要四种行为:创建(Create)、获取(Read)、更新(Update)和销毁(DELETE),就可以组合成其他无数的操作。其实世界万物都是遵循这一规律:生、变、见、灭。这个原则是源自于我们对于数据库表的数据操作:insert(生)、select(见)、update(变)和delete(灭),所以有时候CRUD也写作为RUDI(read update delete insert)。这四个操作是最基本的操作,即无法再细分的操作,通过它们可以构造复杂的操作过程,正如数学上四则运算是数字的最基本的运算一样。


rails console
Role.find_each{|r| puts r.name}


20160822012907_role_migration.rb

class RoleMigration < ActiveRecord::Migration 
    def change 
        Role.find_each do |r| 
            r.reset 
        end 
    end 
end
#创建数据库
$ rake db:create
#删除development数据库
$ rake db:drop RAILS_ENV=development
#回滚事件
$ rake db:rollback
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值