如何从ruby中的数据库获取数据

问题描述:

我有数据库:

class CreateDataintables < ActiveRecord::Migration
  def change
    create_table :windows do |t|
      t.string :window
      t.timestamps
    end

     create_table :channels do |t|
      t.integer :channel
      t.integer     :data
      t.belongs_to :window
      t.timestamps  
    end 


  end
end

我想从测试"窗口通道" 1读取数据/向其中写入数据,但不知道该怎么办.请给我一些示例代码.我真的很需要.

I want to read / write data from/to window "test" , channel "1" but don't know what to do. Give me some example code, please .I really need it.

以下应为模型代码:

Class Window < ActiveRecord::Base
  has_many :channels
end

class Channel < ActiveRecord::Base
  belongs_to :window
end

在控制台中,执行以下操作:

In the console, do the following:

@window = Window.create(window: "This is window-1")

这将创建一个Windows实例并将其保存到数据库中.

This will create a windows-instance and saves it into the database.

100.times do |index|
  Channel.create(channel: Random.rand(1000),
                 data:    Random.rand(1000),
                 window:  @window)
end

这将创建100个属于较早创建的窗口的Channel实例.另外,将它们保存到数据库中.

This will create 100 Channel instances that belong to the earlier-created-window. Also, saves them to the database.

@window.channels将返回相应的100个通道.

@window.channels will return the corresponding 100 channels.

这是您写入/插入记录和读取/读取记录的方式.

This is how you write/insert record and read/fetch record.

请务必阅读 http://edgeguides.rubyonrails.org/active_record_basics.html#create http://edgeguides.rubyonrails.org/active_record_basics.html#read 更好的清晰度和进一步的探索,

Please do read http://edgeguides.rubyonrails.org/active_record_basics.html#create and http://edgeguides.rubyonrails.org/active_record_basics.html#read for better clarity and exploring futher,