跳到內容 跳到搜尋

Active Record – Rails 中的物件關聯對映

Active Record 會將類別連結到關聯式資料庫表格,為應用程式建立近乎零組態的持久化層。該函式庫提供了基本類別,當此類別作為子類別時,會設定新類別與資料庫中現有表格之間的對映。在應用程式的架構中,這些類別通常稱為模型。模型也可以連結到其他模型,這會透過定義關聯來達成。

Active Record 非常依賴命名,它會使用類別和關聯名稱在對應的資料庫表格和外部金鑰欄位之間建立對映。儘管可以明確定義這些對映,但建議遵循命名慣例,特別是在剛開始使用函式庫時。

您可以在 Active Record 基本知識 指南中進一步了解 Active Record。

以下是其中一些主要功能的簡單摘要

  • 自動對映類別和表格、屬性和欄位。

    class Product < ActiveRecord::Base
    end
    

    Product 類別會自動對映到名為「products」的表格,它看起來像這樣

    CREATE TABLE products (
      id bigint NOT NULL auto_increment,
      name varchar(255),
      PRIMARY KEY  (id)
    );
    

    這也會定義以下取用器:Product#nameProduct#name=(new_name)

    了解更多資訊

  • 物件之間的關聯由簡單類別方法定義。

    class Firm < ActiveRecord::Base
      has_many   :clients
      has_one    :account
      belongs_to :conglomerate
    end
    

    了解更多資訊

  • 值物件的集合。

    class Account < ActiveRecord::Base
      composed_of :balance, class_name: 'Money',
                  mapping: %w(balance amount)
      composed_of :address,
                  mapping: [%w(address_street street), %w(address_city city)]
    end
    

    了解更多資訊

  • 新物件或現有物件的驗證規則可能不同。

    class Account < ActiveRecord::Base
      validates :subdomain, :name, :email_address, :password, presence: true
      validates :subdomain, uniqueness: true
      validates :terms_of_service, acceptance: true, on: :create
      validates :password, :email_address, confirmation: true, on: :create
    end
    

    了解更多資訊

  • 適用於整個生命週期(建立實例、儲存、銷毀、驗證,等等)的回呼。

    class Person < ActiveRecord::Base
      before_destroy :invalidate_payment_plan
      # the `invalidate_payment_plan` method gets called just before Person#destroy
    end
    

    了解更多資訊

  • 繼承層級結構。

    class Company < ActiveRecord::Base; end
    class Firm < Company; end
    class Client < Company; end
    class PriorityClient < Client; end
    

    了解更多資訊

  • 交易。

    # Database transaction
    Account.transaction do
      david.withdrawal(100)
      mary.deposit(100)
    end
    

    了解更多資訊

  • 欄位、關聯和集合的反思。

    reflection = Firm.reflect_on_association(:clients)
    reflection.klass # => Client (class)
    Firm.columns # Returns an array of column descriptors for the firms table
    

    了解更多資訊

  • 透過簡單的轉接器進行資料庫抽象。

    # connect to SQLite3
    ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'dbfile.sqlite3')
    
    # connect to MySQL with authentication
    ActiveRecord::Base.establish_connection(
      adapter:  'mysql2',
      host:     'localhost',
      username: 'me',
      password: 'secret',
      database: 'activerecord'
    )
    

    了解更多資訊並深入了解對 MySQLPostgreSQLSQLite3 的內建支援。

  • 支援 Log4rLogger 的記錄。

    ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT)
    ActiveRecord::Base.logger = Log4r::Logger.new('Application Log')
    
  • 透過遷移進行與資料庫無關的綱要管理。

    class AddSystemSettings < ActiveRecord::Migration[8.0]
      def up
        create_table :system_settings do |t|
          t.string  :name
          t.string  :label
          t.text    :value
          t.string  :type
          t.integer :position
        end
    
        SystemSetting.create name: 'notice', label: 'Use notice?', value: 1
      end
    
      def down
        drop_table :system_settings
      end
    end
    

    了解更多資訊

哲學

Active Record 是一個物件關聯對映 (ORM) 模式 的實作,名稱來自 Martin Fowler

「一個包裹資料庫表格或檢視中的列的物件,封裝資料庫存取並針對該資料加入網域邏輯。」

Active Record 嘗試提供一個一致的包裝器,作為物件關聯對映造成的麻煩的一個解決方案。此對映的主要準則在於將建置實際的網域模型所需的程式碼量減到最少。這要透過倚賴許多約定來達成,這些約定讓 Active Record 能夠輕鬆從最少的明確指令推論出複雜的關係和結構。

約定重於組態

  • 沒有 XML 檔案!

  • 大量的反思和執行階段延伸

  • 魔法本身並不是一個壞字

承認資料庫

  • 讓您可針對特殊情況和效能下降進行 SQL

  • 不會嘗試複製或取代資料定義

下載和安裝

可以使用 RubyGems 安裝最新版本的 Active Record

$ gem install activerecord

可以在 GitHub 上下載原始碼,這是 Rails 專案的一部分

授權

Active Record 發布於 MIT 授權之下

支援

API 文件位於

Ruby on Rails 專案的錯誤回報可以提交到這裡

功能要求應該在 rails-core 的郵件列表中進行討論,在這裡