README.rdoc 6.7 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

16 17
You can read more about Active Record in the {Active Record Basics}[https://edgeguides.rubyonrails.org/active_record_basics.html] guide.

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

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

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

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

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

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

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

D
Initial  
David Heinemeier Hansson 已提交
39

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

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

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


51 52 53
* Aggregations of value objects.

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

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


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

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

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


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

   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 已提交
80 81
   end

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


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

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

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


95
* Transactions.
D
Initial  
David Heinemeier Hansson 已提交
96

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

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


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

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

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


115
* Database abstraction through simple adapters.
D
Initial  
David Heinemeier Hansson 已提交
116

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

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

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


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

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


141
* Database agnostic schema management with Migrations.
142

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

153
        SystemSetting.create name: 'notice', label: 'Use notice?', value: 1
154 155
      end

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

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

D
Initial  
David Heinemeier Hansson 已提交
163

164
== Philosophy
D
Initial  
David Heinemeier Hansson 已提交
165

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

M
Mislav Marohnić 已提交
170 171
  "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 已提交
172

173
Active Record attempts to provide a coherent wrapper as a solution for the inconvenience that is
D
Initial  
David Heinemeier Hansson 已提交
174
object-relational mapping. The prime directive for this mapping has been to minimize
175
the amount of code needed to build a real-world domain model. This is made possible
D
Initial  
David Heinemeier Hansson 已提交
176 177 178 179
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 已提交
180
* No XML files!
D
Initial  
David Heinemeier Hansson 已提交
181
* Lots of reflection and run-time extension
182
* Magic is not inherently a bad word
D
Initial  
David Heinemeier Hansson 已提交
183 184 185 186 187 188

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


189
== Download and installation
D
Initial  
David Heinemeier Hansson 已提交
190

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

193
  $ gem install activerecord
D
Initial  
David Heinemeier Hansson 已提交
194

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

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


== License

202 203
Active Record is released under the MIT license:

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


== Support

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

211
* https://api.rubyonrails.org
D
Initial  
David Heinemeier Hansson 已提交
212

F
Fatos Morina 已提交
213
Bug reports for the Ruby on Rails project can be filed here:
214

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

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

219
* https://discuss.rubyonrails.org/c/rubyonrails-core