我有数据库:
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读取数据,或将数据写入其中,但不知道该怎么办。请给我一些示例代码。我真的很需要它。
以下应该是模型代码:
Class Window < ActiveRecord::Base
has_many :channels
end
class Channel < ActiveRecord::Base
belongs_to :window
end
在控制台中,执行以下操作:
@window = Window.create(window: "This is window-1")
这将创建一个Windows实例并将其保存到数据库中。
100.times do |index|
Channel.create(channel: Random.rand(1000),
data: Random.rand(1000),
window: @window)
end
这将创建100个属于早期创建的窗口的Channel实例。另外,将它们保存到数据库。
@window.channels
将返回相应的100个频道。
这就是您写入/插入记录和读取/读取记录的方式。
请阅读http://edgeguides.rubyonrails.org/active_record_basics.html#create和http://edgeguides.rubyonrails.org/active_record_basics.html#read以获得更好的清晰度和进一步的了解,
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句