README.rdoc 6.5 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 49 50


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

51
    class Account < ActiveRecord::Base
52 53 54 55
      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
56
    end
D
Initial  
David Heinemeier Hansson 已提交
57

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


61
* Callbacks available for the entire life cycle (instantiation, saving, destroying, validating, etc.).
M
Mislav Marohnić 已提交
62 63 64 65

   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 已提交
66 67
   end

68
  {Learn more}[link:classes/ActiveRecord/Callbacks.html]
D
Initial  
David Heinemeier Hansson 已提交
69 70


71
* Observers that react to changes in a model.
D
Initial  
David Heinemeier Hansson 已提交
72 73 74

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

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


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

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

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


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

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

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


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

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

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


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

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

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

M
Mislav Marohnić 已提交
126 127 128 129
  {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 已提交
130 131


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

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


138
* Database agnostic schema management with Migrations.
139 140

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

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

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

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

D
Initial  
David Heinemeier Hansson 已提交
160

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

M
Mislav Marohnić 已提交
163 164 165
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 已提交
166

M
Mislav Marohnić 已提交
167 168
  "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 已提交
169

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

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


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

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

190
  % [sudo] gem install activerecord
D
Initial  
David Heinemeier Hansson 已提交
191

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

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


== License

199 200 201
Active Record is released under the MIT license:

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


== Support

206
API documentation is at
D
Initial  
David Heinemeier Hansson 已提交
207

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

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

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