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\n", disk.mnt_point, disk.dev_name, disk.reports.last.m\
b_used, disk.mb_available
  end
end
posted @ 2015-07-31 20:43  梅西爸爸  阅读(223)  评论(0编辑  收藏  举报