如何从 ruby 中的数据库中获取数据 [英] How can I get data from database in ruby
问题描述
I have database:
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
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.
Following should be Model code:
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")
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
This will create 100 Channel instances that belong to the earlier-created-window. Also, saves them to the database.
@window.channels
will return the corresponding 100 channels.
This is how you write/insert record and read/fetch record.
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,
这篇关于如何从 ruby 中的数据库中获取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!