README.rdoc 6.6 KB
Newer Older
V
Vijay Dev 已提交
1
= Active Record -- Object-relational mapping in Rails
D
Initial  
David Heinemeier Hansson 已提交
2

M
Mislav Marohnić 已提交
3 4 5
Active Record connects classes to relational database tables to establish an
almost zero-configuration persistence layer for applications. The library
provides a base class that, when subclassed, sets up a mapping between the new
6
class and an existing table in the database. In the context of an application,
M
Mislav Marohnić 已提交
7 8
these classes are commonly referred to as *models*. Models can also be
connected to other models; this is done by defining *associations*.
D
Initial  
David Heinemeier Hansson 已提交
9

M
Mislav Marohnić 已提交
10 11 12 13 14
Active Record relies heavily on naming in that it uses class and association
names to establish mappings between respective database tables and foreign key
columns. Although these mappings can be defined explicitly, it's recommended
to follow naming conventions, especially when getting started with the
library.
D
Initial  
David Heinemeier Hansson 已提交
15

M
Mislav Marohnić 已提交
16
A short rundown of some of the major features:
D
Initial  
David Heinemeier Hansson 已提交
17 18 19

* Automated mapping between classes and tables, attributes and columns.

M
Mislav Marohnić 已提交
20 21
   class Product < ActiveRecord::Base
   end
Z
Zachary Scott 已提交
22

V
Vijay Dev 已提交
23
  {Learn more}[link:classes/ActiveRecord/Base.html]
Z
Zachary Scott 已提交
24

G
Gaurish Sharma 已提交
25 26
The Product class is automatically mapped to the table named "products",
which might look like this:
27

D
Initial  
David Heinemeier Hansson 已提交
28
   CREATE TABLE products (
29
     id int NOT NULL auto_increment,
D
Initial  
David Heinemeier Hansson 已提交
30 31 32
     name varchar(255),
     PRIMARY KEY  (id)
   );
33

34 35
This would also define the following accessors: <tt>Product#name</tt> and
<tt>Product#name=(new_name)</tt>.
Z
Zachary Scott 已提交
36

D
Initial  
David Heinemeier Hansson 已提交
37

M
Mislav Marohnić 已提交
38
* Associations between objects defined by simple class methods.
D
Initial  
David Heinemeier Hansson 已提交
39 40 41 42

   class Firm < ActiveRecord::Base
     has_many   :clients
     has_one    :account
M
Mislav Marohnić 已提交
43
     belongs_to :conglomerate
D
Initial  
David Heinemeier Hansson 已提交
44 45
   end

46
  {Learn more}[link:classes/ActiveRecord/Associations/ClassMethods.html]
D
Initial  
David Heinemeier Hansson 已提交
47 48


49 50 51
* Aggregations of value objects.

   class Account < ActiveRecord::Base
52 53
     composed_of :balance, class_name: 'Money',
                 mapping: %w(balance amount)
54
     composed_of :address,
55
                 mapping: [%w(address_street street), %w(address_city city)]
56 57 58 59 60
   end

  {Learn more}[link:classes/ActiveRecord/Aggregations/ClassMethods.html]


D
Initial  
David Heinemeier Hansson 已提交
61 62
* Validation rules that can differ for new or existing objects.

63
    class Account < ActiveRecord::Base
64 65 66 67
      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
68
    end
D
Initial  
David Heinemeier Hansson 已提交
69

70
  {Learn more}[link:classes/ActiveRecord/Validations.html]
D
Initial  
David Heinemeier Hansson 已提交
71 72


73
* Callbacks available for the entire life cycle (instantiation, saving, destroying, validating, etc.).
M
Mislav Marohnić 已提交
74 75 76 77

   class Person < ActiveRecord::Base
     before_destroy :invalidate_payment_plan
     # the `invalidate_payment_plan` method gets called just before Person#destroy
D
Initial  
David Heinemeier Hansson 已提交
78 79
   end

80
  {Learn more}[link:classes/ActiveRecord/Callbacks.html]
D
Initial  
David Heinemeier Hansson 已提交
81 82


83
* Inheritance hierarchies.
D
Initial  
David Heinemeier Hansson 已提交
84 85 86 87 88 89

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

90
  {Learn more}[link:classes/ActiveRecord/Base.html]
D
Initial  
David Heinemeier Hansson 已提交
91 92


93
* Transactions.
D
Initial  
David Heinemeier Hansson 已提交
94

P
Pratik Naik 已提交
95
    # Database transaction
D
Initial  
David Heinemeier Hansson 已提交
96 97 98 99 100
    Account.transaction do
      david.withdrawal(100)
      mary.deposit(100)
    end

101
  {Learn more}[link:classes/ActiveRecord/Transactions/ClassMethods.html]
D
Initial  
David Heinemeier Hansson 已提交
102 103


104
* Reflections on columns, associations, and aggregations.
D
Initial  
David Heinemeier Hansson 已提交
105 106 107 108 109

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

110
  {Learn more}[link:classes/ActiveRecord/Reflection/ClassMethods.html]
D
Initial  
David Heinemeier Hansson 已提交
111 112


113
* Database abstraction through simple adapters.
D
Initial  
David Heinemeier Hansson 已提交
114

M
Mislav Marohnić 已提交
115
    # connect to SQLite3
116
    ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: 'dbfile.sqlite3')
D
Initial  
David Heinemeier Hansson 已提交
117

M
Mislav Marohnić 已提交
118 119
    # connect to MySQL with authentication
    ActiveRecord::Base.establish_connection(
120 121 122 123 124
      adapter:  'mysql2',
      host:     'localhost',
      username: 'me',
      password: 'secret',
      database: 'activerecord'
M
Mislav Marohnić 已提交
125
    )
D
Initial  
David Heinemeier Hansson 已提交
126

M
Mislav Marohnić 已提交
127
  {Learn more}[link:classes/ActiveRecord/Base.html] and read about the built-in support for
R
Ryuta Kamizono 已提交
128
  MySQL[link:classes/ActiveRecord/ConnectionAdapters/Mysql2Adapter.html],
M
Mislav Marohnić 已提交
129 130
  PostgreSQL[link:classes/ActiveRecord/ConnectionAdapters/PostgreSQLAdapter.html], and
  SQLite3[link:classes/ActiveRecord/ConnectionAdapters/SQLite3Adapter.html].
D
Initial  
David Heinemeier Hansson 已提交
131 132


133
* Logging support for Log4r[https://github.com/colbygk/log4r] and Logger[http://www.ruby-doc.org/stdlib/libdoc/logger/rdoc].
D
Initial  
David Heinemeier Hansson 已提交
134

135
    ActiveRecord::Base.logger = ActiveSupport::Logger.new(STDOUT)
136
    ActiveRecord::Base.logger = Log4r::Logger.new('Application Log')
D
Initial  
David Heinemeier Hansson 已提交
137 138


139
* Database agnostic schema management with Migrations.
140

141
    class AddSystemSettings < ActiveRecord::Migration[5.0]
A
Akira Matsuda 已提交
142
      def up
143
        create_table :system_settings do |t|
M
Mislav Marohnić 已提交
144 145 146 147 148
          t.string  :name
          t.string  :label
          t.text    :value
          t.string  :type
          t.integer :position
149 150
        end

151
        SystemSetting.create name: 'notice', label: 'Use notice?', value: 1
152 153
      end

A
Akira Matsuda 已提交
154
      def down
155 156 157 158 159 160
        drop_table :system_settings
      end
    end

  {Learn more}[link:classes/ActiveRecord/Migration.html]

D
Initial  
David Heinemeier Hansson 已提交
161

162
== Philosophy
D
Initial  
David Heinemeier Hansson 已提交
163

M
Mislav Marohnić 已提交
164
Active Record is an implementation of the object-relational mapping (ORM)
165
pattern[https://www.martinfowler.com/eaaCatalog/activeRecord.html] by the same
M
Mislav Marohnić 已提交
166
name described by Martin Fowler:
D
Initial  
David Heinemeier Hansson 已提交
167

M
Mislav Marohnić 已提交
168 169
  "An object that wraps a row in a database table or view,
  encapsulates the database access, and adds domain logic on that data."
D
Initial  
David Heinemeier Hansson 已提交
170

171
Active Record attempts to provide a coherent wrapper as a solution for the inconvenience that is
D
Initial  
David Heinemeier Hansson 已提交
172
object-relational mapping. The prime directive for this mapping has been to minimize
173
the amount of code needed to build a real-world domain model. This is made possible
D
Initial  
David Heinemeier Hansson 已提交
174 175 176 177
by relying on a number of conventions that make it easy for Active Record to infer
complex relations and structures from a minimal amount of explicit direction.

Convention over Configuration:
W
Waynn Lue 已提交
178
* No XML files!
D
Initial  
David Heinemeier Hansson 已提交
179
* Lots of reflection and run-time extension
180
* Magic is not inherently a bad word
D
Initial  
David Heinemeier Hansson 已提交
181 182 183 184 185 186

Admit the Database:
* Lets you drop down to SQL for odd cases and performance
* Doesn't attempt to duplicate or replace data definitions


187
== Download and installation
D
Initial  
David Heinemeier Hansson 已提交
188

S
Sukeerthi Adiga 已提交
189
The latest version of Active Record can be installed with RubyGems:
D
Initial  
David Heinemeier Hansson 已提交
190

191
  $ gem install activerecord
D
Initial  
David Heinemeier Hansson 已提交
192

W
Waynn Lue 已提交
193
Source code can be downloaded as part of the Rails project on GitHub:
D
Initial  
David Heinemeier Hansson 已提交
194

195
* https://github.com/rails/rails/tree/master/activerecord
D
Initial  
David Heinemeier Hansson 已提交
196 197 198 199


== License

200 201
Active Record is released under the MIT license:

202
* https://opensource.org/licenses/MIT
D
Initial  
David Heinemeier Hansson 已提交
203 204 205 206


== Support

W
Waynn Lue 已提交
207
API documentation is at:
D
Initial  
David Heinemeier Hansson 已提交
208

209
* http://api.rubyonrails.org
D
Initial  
David Heinemeier Hansson 已提交
210

211
Bug reports can be filed for the Ruby on Rails project here:
212

A
Arun Agrawal 已提交
213
* https://github.com/rails/rails/issues
214 215 216 217

Feature requests should be discussed on the rails-core mailing list here:

* https://groups.google.com/forum/?fromgroups#!forum/rubyonrails-core