ruby 功力修炼
2015-07-31 20:43
357 查看
建表
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
相关文章推荐
- macosx zsh下安装rvm和ruby
- ruby环境sass编译中文出现Syntax error: Invalid GBK character错误解决方法
- RubySpec 重生:破蛹成蝶
- Ruby学习总结
- ruby 遍历mongo数据
- ruby 遍历mongo数据
- 嵌Ruby 2 《捆绑》
- 测试驱动开发 Ruby 命令行工具实战
- win7安装ruby on rails开发环境
- 为什么我们应该为Ruby2.0的GC感到excited!
- 关于Ruby的GC
- selinium的ruby版在windows8下安装
- Ruby 中的类和对象
- ruby中数组的常用函数
- Ruby
- 手把手教学:巧用Core Data和RubyMotion开发iOS应用
- Ruby 程序员最要好的朋友
- 安装ruby环境
- Installing MySQL Ruby Gem checking for mysql_ssl_set()... no
- ruby bundle信任goagent证书