跳至内容 跳至搜索

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')
    
  • 使用 Migrations 进行数据库无关的模式管理。

    class AddSystemSettings < ActiveRecord::Migration[8.1]
      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 是马丁·福勒(Martin Fowler)所描述的同名对象关系映射(ORM)模式 的实现

“一个包装数据库表或视图中的一行,封装数据库访问,并在这些数据上添加域逻辑的对象。”

Active Record 尝试提供一个连贯的包装器作为对象关系映射不便之处的解决方案。此映射的首要目标是最大限度地减少构建真实域模型所需的代码量。这可以通过依赖许多约定来实现,这些约定使得 Active Record 能够轻松地从最少的显式指令推断出复杂的关联和结构。

约定优于配置

  • 无 XML 文件!

  • 大量反射和运行时扩展

  • 魔法并非必然是坏词

承认数据库

  • 允许您在特殊情况和性能问题时降级到 SQL

  • 不尝试复制或替换数据定义

下载和安装

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

$ gem install activerecord

源代码可以作为 Rails 项目的一部分在 GitHub 上下载。

许可证

Active Record 在 MIT 许可下发布

支持

API 文档位于:

Ruby on Rails 项目的错误报告可在此处提交:

功能请求应在此处的 rubyonrails-core 论坛上讨论: