zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    第三次冲刺--软件工程
    【操作系统】实验四 主存空间的分配和回收
    《构造之法》8、9、10
    实验三 进程调度模拟程序--操作系统
    构建之法读后感
    操作系统作业调度-操作系统
    结对评论—软件工程
    复利计算6.0—软件工程(web版本)
    学习进度条
    第三次冲刺总结
  • 原文地址:https://www.cnblogs.com/messipapa/p/4693105.html
Copyright © 2011-2022 走看看