README.rdoc 6.8 KB
Newer Older
M
Mislav Marohnić 已提交
1
= Active Record -- Object-relational mapping put on 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
22

M
Mislav Marohnić 已提交
23 24
   The Product class is automatically mapped to the table named "products",
   which might look like this:
25

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

M
Mislav Marohnić 已提交
32 33
   This would also define the following accessors: `Product#name` and
   `Product#name=(new_name)`
34

35
  {Learn more}[link:classes/ActiveRecord/Base.html]
D
Initial  
David Heinemeier Hansson 已提交
36 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


M
Mislav Marohnić 已提交
49
* Aggregations of value objects.
D
Initial  
David Heinemeier Hansson 已提交
50 51 52 53

   class Account < ActiveRecord::Base
     composed_of :balance, :class_name => "Money",
                 :mapping => %w(balance amount)
54
     composed_of :address,
D
Initial  
David Heinemeier Hansson 已提交
55 56 57
                 :mapping => [%w(address_street street), %w(address_city city)]
   end

58
  {Learn more}[link:classes/ActiveRecord/Aggregations/ClassMethods.html]
D
Initial  
David Heinemeier Hansson 已提交
59 60 61 62


* Validation rules that can differ for new or existing objects.

63 64 65 66 67 68
    class Account < ActiveRecord::Base
      validates_presence_of     :subdomain, :name, :email_address, :password
      validates_uniqueness_of   :subdomain
      validates_acceptance_of   :terms_of_service, :on => :create
      validates_confirmation_of :password, :email_address, :on => :create
    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
* Observers that react to changes in a model.
D
Initial  
David Heinemeier Hansson 已提交
84 85 86

   class CommentObserver < ActiveRecord::Observer
     def after_create(comment) # is called just after Comment#save
87
       CommentMailer.new_comment_email("david@loudthinking.com", comment).deliver
D
Initial  
David Heinemeier Hansson 已提交
88 89 90
     end
   end

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


94
* Inheritance hierarchies.
D
Initial  
David Heinemeier Hansson 已提交
95 96 97 98 99 100

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

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


104
* Transactions.
D
Initial  
David Heinemeier Hansson 已提交
105

P
Pratik Naik 已提交
106
    # Database transaction
D
Initial  
David Heinemeier Hansson 已提交
107 108 109 110 111
    Account.transaction do
      david.withdrawal(100)
      mary.deposit(100)
    end

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


115
* Reflections on columns, associations, and aggregations.
D
Initial  
David Heinemeier Hansson 已提交
116 117 118 119 120

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

121
  {Learn more}[link:classes/ActiveRecord/Reflection/ClassMethods.html]
D
Initial  
David Heinemeier Hansson 已提交
122 123


124
* Database abstraction through simple adapters.
D
Initial  
David Heinemeier Hansson 已提交
125

M
Mislav Marohnić 已提交
126 127
    # connect to SQLite3
    ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => "dbfile.sqlite3")
D
Initial  
David Heinemeier Hansson 已提交
128

M
Mislav Marohnić 已提交
129 130
    # connect to MySQL with authentication
    ActiveRecord::Base.establish_connection(
131
      :adapter  => "mysql2",
M
Mislav Marohnić 已提交
132 133 134 135 136
      :host     => "localhost",
      :username => "me",
      :password => "secret",
      :database => "activerecord"
    )
D
Initial  
David Heinemeier Hansson 已提交
137

M
Mislav Marohnić 已提交
138 139 140 141
  {Learn more}[link:classes/ActiveRecord/Base.html] and read about the built-in support for
  MySQL[link:classes/ActiveRecord/ConnectionAdapters/MysqlAdapter.html],
  PostgreSQL[link:classes/ActiveRecord/ConnectionAdapters/PostgreSQLAdapter.html], and
  SQLite3[link:classes/ActiveRecord/ConnectionAdapters/SQLite3Adapter.html].
D
Initial  
David Heinemeier Hansson 已提交
142 143


144
* Logging support for Log4r[http://log4r.sourceforge.net] and Logger[http://www.ruby-doc.org/stdlib/libdoc/logger/rdoc].
D
Initial  
David Heinemeier Hansson 已提交
145 146 147 148 149

    ActiveRecord::Base.logger = Logger.new(STDOUT)
    ActiveRecord::Base.logger = Log4r::Logger.new("Application Log")


150
* Database agnostic schema management with Migrations.
151 152 153 154

    class AddSystemSettings < ActiveRecord::Migration
      def self.up
        create_table :system_settings do |t|
M
Mislav Marohnić 已提交
155 156 157 158 159
          t.string  :name
          t.string  :label
          t.text    :value
          t.string  :type
          t.integer :position
160 161 162 163 164 165 166 167 168 169 170 171
        end

        SystemSetting.create :name => "notice", :label => "Use notice?", :value => 1
      end

      def self.down
        drop_table :system_settings
      end
    end

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

D
Initial  
David Heinemeier Hansson 已提交
172

173
== Philosophy
D
Initial  
David Heinemeier Hansson 已提交
174

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

M
Mislav Marohnić 已提交
179 180
  "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 已提交
181

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

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


198
== Download and installation
D
Initial  
David Heinemeier Hansson 已提交
199

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

202
  % [sudo] gem install activerecord
D
Initial  
David Heinemeier Hansson 已提交
203

204
Source code can be downloaded as part of the Rails project on GitHub
D
Initial  
David Heinemeier Hansson 已提交
205

206
* https://github.com/rails/rails/tree/master/activerecord
D
Initial  
David Heinemeier Hansson 已提交
207 208 209 210


== License

211
Active Record is released under the MIT license.
D
Initial  
David Heinemeier Hansson 已提交
212 213 214 215


== Support

216
API documentation is at
D
Initial  
David Heinemeier Hansson 已提交
217

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

220 221
Bug reports and feature requests can be filed with the rest for the Ruby on Rails project here:

A
Arun Agrawal 已提交
222
* https://github.com/rails/rails/issues