Ruby on rails開發從頭來(三十八)- ActiveRecord基礎(列和屬性)

來源:互聯網
上載者:User

ActiveRecord中的一個對象相當於資料庫中表的一行,對象的屬性對應於表的列,也許你會注意到我們的Order類沒有提及關於orders表的任何東西,這是因為ActiveRecord在運行時來確定這些對應關係,Active Record將資料庫中的模式反應到類中。

我們的orders表可能使用下面的sql來建立:

create table orders (id int not null auto_increment,name varchar(100) not null,email varchar(255) not null,address text not null,pay_type char(10) not null,shipped_at datetime null,primary key (id));

我們可以建立一個類來轉換這個表:

require 'rubygems'require_gem 'activerecord'# Connection code omitted...class Order < ActiveRecord::Baseend

當我們建立了Order類,就可以訪問它的屬性來擷取資訊,下面的代碼使用columns()方法,來返回一個Columns對象的數組,在這裡,我們顯示了orders表中的每個列,並且顯示指定欄位的詳細資料。

require 'pp'pp Order.columns.map { |col| col.name }pp Order.columns_hash['shipped_at']

運行代碼,會得到下面的輸出:

["id", "name", "email", "address", "pay_type", "shipped_at"]#<ActiveRecord::ConnectionAdapters::Column:0x10e4a50@default=nil,@limit=nil,@name="shipped_at",@type=:datetime>

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.