如何从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
我想从/向窗口“test”读取/写入数据,通道“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-instance并将其保存到数据库中。
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以获得更好的清晰度并进一步探索,
你真的需要回到绘图板,老兄。
大多数rails初学者都是从twitter克隆教程开始的,至少这就是我所做的。
以下是我第一次开始使用ActiveRecord时使用的codeschool.com免费课程https://www.codeschool.com/courses/rails-for-zombies-redux