• ruby 功力修炼


    建表

    ActiveRecord::Schema.define do
      drop_table :hosts if table_exists? :hosts
      create_table :hosts do |table|
        table.column :name, :string
      end
    
      drop_table :disks if table_exists? :disks
      create_table :disks do |table|
        table.column :host_id, :integer
        table.column :dev_name, :string
        table.column :mnt_point, :string
        table.column :mb_available, :integer
      end
    
      drop_table :reports if table_exists? :reports
      create_table :reports do |table|
        table.column :disk_id, :integer
        table.column :created_at, :datetime
        table.column :mb_used, :integer
      end
    end
    

    上述代码总共创建了 :hosts、:disks和:reports三张表。

    网络上找到的绝大多数示例都没有drop_table这句话,我个人认为练习的时候会频繁地测试,加上自动删除才是完整的步骤。

    此处的功能应该就是对应Rails里migration过程。

    5. 定义模型

    这一步进入正题,定义在代码中使用的对象,即数据模型

    class Host < ActiveRecord::Base
      has_many :disks
    end
    
    class Disk < ActiveRecord::Base
      belongs_to :host
      has_many :reports
    end
    
    class Report < ActiveRecord::Base
      belongs_to :disk
    end
    

    对象与之前定义的表一一对应,其中用belongs_to和has_many等宏声明了对象/表之间的联系。根据DRY原则,此处无需再定义表的字段!

    这一步就是在Rails中定义model的过程。

    6. 生成数据

    host = Host.create(:name => "slarti")
    disk = host.disks.create(:dev_name => "/dev/disk1s1",
                             :mnt_point => "/",
                             :mb_available => 80 * 1024)
    disk.reports.create(:mb_used => 20 * 1024)
    disk.reports.create(:mb_used => 25 * 1024)
    

    通过操作上一步定义的数据模型即可实现插入数据。

    7. 检索

    Host.all.each do |host|
      puts "*** #{host.name} ***"
      host.disks.each do |disk|
        printf "%s(%s) %d/%d
    ", disk.mnt_point, disk.dev_name, disk.reports.last.m
    b_used, disk.mb_available
      end
    end
    
  • 相关阅读:
    JS实战 · 表单验证
    JS实战 · 仿css样式选择器
    JS实战 ·  收缩菜单表单布局
    cookie自动登录的实现
    redis 3.2.5单机版安装、使用、systemctl管理Redis启动、停止、开机启动
    yum问题解决
    配置yum镜像源
    shell笔记
    CCIE总结:路由器、交换机
    云主机如何挂在磁盘
  • 原文地址:https://www.cnblogs.com/messipapa/p/4693105.html
Copyright © 2020-2023  润新知