如何从 ruby​​ 中的数据库中获取数据 [英] How can I get data from database in ruby

查看:17
本文介绍了如何从 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆