This repository has been archived by the owner on Jan 7, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
active_record_basics.html
403 lines (375 loc) · 23.5 KB
/
active_record_basics.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Ruby on Rails Guides: Active Record Basics</title>
<link rel="stylesheet" type="text/css" href="stylesheets/style.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/print.css" media="print" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shCore.css" />
<link rel="stylesheet" type="text/css" href="stylesheets/syntaxhighlighter/shThemeRailsGuides.css" />
</head>
<body class="guide">
<div id="topNav">
<div class="wrapper">
<strong>More at <a href="http://rubyonrails.org/">rubyonrails.org:</a> </strong>
<a href="http://rubyonrails.org/">Overview</a> |
<a href="http://rubyonrails.org/download">Download</a> |
<a href="http://rubyonrails.org/deploy">Deploy</a> |
<a href="http://rails.lighthouseapp.com/projects/8994-ruby-on-rails/overview">Code</a> |
<a href="http://rubyonrails.org/screencasts">Screencasts</a> |
<a href="http://rubyonrails.org/documentation">Documentation</a> |
<a href="http://rubyonrails.org/ecosystem">Ecosystem</a> |
<a href="http://rubyonrails.org/community">Community</a> |
<a href="http://weblog.rubyonrails.org/">Blog</a>
</div>
</div>
<div id="header">
<div class="wrapper clearfix">
<h1><a href="index.html" title="Return to home page">Guides.rubyonrails.org</a></h1>
<p class="hide"><a href="#mainCol">Skip navigation</a>.</p>
<ul class="nav">
<li><a href="index.html">홈</a></li>
<li class="index"><a href="index.html" onclick="guideMenu(); return false;" id="guidesMenu">목차</a>
<div id="guides" class="clearfix" style="display: none;">
<hr />
<dl class="L">
<dt>시작</dt>
<dd><a href="getting_started.html">레일즈 시작하기</a></dd>
<dt>모델(Models)</dt>
<dd><a href="migrations.html">레일즈 데이터베이스 마이그레이션</a></dd>
<dd><a href="active_record_validations_callbacks.html">액티브 레코드 데이터 검증(Validation)과 Callback(콜백)</a></dd>
<dd><a href="association_basics.html">액티브 레코드 Association(관계)</a></dd>
<dd><a href="active_record_querying.html">액티브 레코드 쿼리 인터페이스</a></dd>
<dt>뷰(Views)</dt>
<dd><a href="layouts_and_rendering.html">레이아웃(Layouts)과 렌더링(Rendering)</a></dd>
<dd><a href="form_helpers.html">액션 뷰 폼 핼퍼(Action View Form Helpers)</a></dd>
<dt>컨트롤러(Controllers)</dt>
<dd><a href="action_controller_overview.html">액션 컨트롤러 둘러보기</a></dd>
<dd><a href="routing.html">외부 요청에 대한 레일즈 라우팅</a></dd>
</dl>
<dl class="R">
<dt>심화내용</dt>
<dd><a href="active_support_core_extensions.html">액티브 서포트(Active Support) 확장(Core Extensions)</a></dd>
<dd><a href="i18n.html">레일즈 국제화I(nternationalization) API</a></dd>
<dd><a href="action_mailer_basics.html">액션 메일러의 기본</a></dd>
<dd><a href="testing.html">레일즈 어플리케이션 테스트하기</a></dd>
<dd><a href="security.html">레일즈 어플리케이션의 보안</a></dd>
<dd><a href="debugging_rails_applications.html">레일즈 어플리케이션 디버깅</a></dd>
<dd><a href="performance_testing.html">레일즈 어플리케이션 성능 테스트하기</a></dd>
<dd><a href="configuring.html">레일즈 어플리케이션 설정</a></dd>
<dd><a href="command_line.html">레일즈 커멘드라인 도구와 Rake 테스크</a></dd>
<dd><a href="caching_with_rails.html">레일즈를 이용한 캐싱</a></dd>
<dt>레일즈 확장하기(Extending Rails)</dt>
<dd><a href="plugins.html">레일즈 플러그인 작성의 기본</a></dd>
<dd><a href="rails_on_rack.html">렉 위의 레일즈(Rails on Rack)</a></dd>
<dd><a href="generators.html">레일즈 제너레이터(Generator) 제작과 수정</a></dd>
<dt>루비 온 레이즈에 기여하기</dt>
<dd><a href="contributing_to_ruby_on_rails.html">루비 온 레이즈에 기여하기</a></dd>
<dd><a href="api_documentation_guidelines.html">API 문서 가이드라인</a></dd>
<dd><a href="ruby_on_rails_guides_guidelines.html">루비 온 레일즈 가이드에 대한 가이드라인</a></dd>
<dt>Release Notes</dt>
<dd><a href="3_0_release_notes.html">Ruby on Rails 3.0 Release Notes</a></dd>
<dd><a href="2_3_release_notes.html">Ruby on Rails 2.3 Release Notes</a></dd>
<dd><a href="2_2_release_notes.html">Ruby on Rails 2.2 Release Notes</a></dd>
</dl>
</div>
</li>
<li><a href="contribute.html">기여하기</a></li>
<li><a href="credits.html">수고하신 분들</a></li>
</ul>
</div>
</div>
<hr class="hide" />
<div id="feature">
<div class="wrapper">
<h2>Active Record Basics</h2>
<p>This guide is an introduction to Active Record. After reading this guide we hope that you’ll learn:</p>
<ul>
<li>What Object Relational Mapping and Active Record are and how they are used in Rails</li>
<li>How Active Record fits into the Model-View-Controller paradigm</li>
<li>How to use Active Record models to manipulate data stored in a relational database</li>
<li>Active Record schema naming conventions</li>
<li>The concepts of database migrations, validations and callbacks</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#what-is-active-record">What is Active Record?</a><ul><li><a href="#the-active-record-pattern">The Active Record Pattern</a></li> <li><a href="#object-relational-mapping">Object Relational Mapping</a></li> <li><a href="#active-record-as-an-orm-framework">Active Record as an <span class="caps">ORM</span> Framework</a></li></ul></li><li><a href="#convention-over-configuration-in-active-record">Convention over Configuration in Active Record</a><ul><li><a href="#naming-conventions">Naming Conventions</a></li> <li><a href="#schema-conventions">Schema Conventions</a></li></ul></li><li><a href="#creating-active-record-models">Creating Active Record Models</a></li><li><a href="#overriding-the-naming-conventions">Overriding the Naming Conventions</a></li><li><a href="#reading-and-writing-data">Reading and Writing Data</a><ul><li><a href="#create">Create</a></li> <li><a href="#read">Read</a></li> <li><a href="#update">Update</a></li> <li><a href="#delete">Delete</a></li></ul></li><li><a href="#validations">Validations</a></li><li><a href="#callbacks">Callbacks</a></li><li><a href="#migrations">Migrations</a></li></ol></div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<h3 id="what-is-active-record">1 What is Active Record?</h3>
<p>Active Record is the M in <a href="getting_started.html#the-mvc-architecture"><span class="caps">MVC</span></a> – the model – which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database. It is an implementation of the Active Record pattern which itself is a description of an Object Relational Mapping system.</p>
<h4 id="the-active-record-pattern">1.1 The Active Record Pattern</h4>
<p>Active Record was described by Martin Fowler in his book <em>Patterns of Enterprise Application Architecture</em>. In Active Record, objects carry both persistent data and behavior which operates on that data. Active Record takes the opinion that ensuring data access logic is part of the object will educate users of that object on how to write to and read from the database.</p>
<h4 id="object-relational-mapping">1.2 Object Relational Mapping</h4>
<p>Object-Relational Mapping, commonly referred to as its abbreviation <span class="caps">ORM</span>, is a technique that connects the rich objects of an application to tables in a relational database management system. Using <span class="caps">ORM</span>, the properties and relationships of the objects in an application can be easily stored and retrieved from a database without writing <span class="caps">SQL</span> statements directly and with less overall database access code.</p>
<h4 id="active-record-as-an-orm-framework">1.3 Active Record as an <span class="caps">ORM</span> Framework</h4>
<p>Active Record gives us several mechanisms, the most important being the ability to:</p>
<ul>
<li>Represent models and their data</li>
<li>Represent associations between these models</li>
<li>Represent inheritance hierarchies through related models</li>
<li>Validate models before they get persisted to the database</li>
<li>Perform database operations in an object-oriented fashion.</li>
</ul>
<h3 id="convention-over-configuration-in-active-record">2 Convention over Configuration in Active Record</h3>
<p>When writing applications using other programming languages or frameworks, it may be necessary to write a lot of configuration code. This is particularly true for <span class="caps">ORM</span> frameworks in general. However, if you follow the conventions adopted by Rails, you’ll need to write very little configuration (in some case no configuration at all) when creating Active Record models. The idea is that if you configure your applications in the very same way most of the times then this should be the default way. In this cases, explicit configuration would be needed only in those cases where you can’t follow the conventions for any reason.</p>
<h4 id="naming-conventions">2.1 Naming Conventions</h4>
<p>By default, Active Record uses some naming conventions to find out how the mapping between models and database tables should be created. Rails will pluralize your class names to find the respective database table. So, for a class <tt>Book</tt>, you should have a database table called <strong>books</strong>. The Rails pluralization mechanisms are very powerful, being capable to pluralize (and singularize) both regular and irregular words. When using class names composed of two or more words, the model class name should follow the Ruby conventions, using the camelCase form, while the table name must contain the words separated by underscores. Examples:</p>
<ul>
<li>Database Table – Plural with underscores separating words (e.g., book_clubs)</li>
<li>Model Class – Singular with the first letter of each word capitalized (e.g., BookClub)</li>
</ul>
<table>
<tr>
<th>Model / Class </th>
<th>Table / Schema </th>
</tr>
<tr>
<td>Post </td>
<td>posts</td>
</tr>
<tr>
<td>LineItem </td>
<td>line_items</td>
</tr>
<tr>
<td>Deer </td>
<td>deer</td>
</tr>
<tr>
<td>Mouse </td>
<td>mice</td>
</tr>
<tr>
<td>Person </td>
<td>people</td>
</tr>
</table>
<h4 id="schema-conventions">2.2 Schema Conventions</h4>
<p>Active Record uses naming conventions for the columns in database tables, depending on the purpose of these columns.</p>
<ul>
<li><strong>Foreign keys</strong> – These fields should be named following the pattern table_id (e.g., item_id, order_id). These are the fields that Active Record will look for when you create associations between your models.</li>
<li><strong>Primary keys</strong> – By default, Active Record will use an integer column named “id” as the table’s primary key. When using <a href="migrations.html">Rails Migrations</a> to create your tables, this column will be automatically created.</li>
</ul>
<p>There are also some optional column names that will create additional features to Active Record instances:</p>
<ul>
<li><strong>created_at</strong> – Automatically gets set to the current date and time when the record is first created.</li>
<li><strong>created_on</strong> – Automatically gets set to the current date when the record is first created.</li>
<li><strong>updated_at</strong> – Automatically gets set to the current date and time whenever the record is updated.</li>
<li><strong>updated_on</strong> – Automatically gets set to the current date whenever the record is updated.</li>
<li><strong>lock_version</strong> – Adds <a href="http://api.rubyonrails.com/classes/ActiveRecord/Locking.html">optimistic locking</a> to a model.</li>
<li><strong>type</strong> – Specifies that the model uses <a href="http://api.rubyonrails.com/classes/ActiveRecord/Base.html">Single Table Inheritance</a></li>
<li><strong class="table_name">_count</strong> – Used to cache the number of belonging objects on associations. For example, a <tt>comments_count</tt> column in a <tt>Post</tt> class that has many instances of <tt>Comment</tt> will cache the number of existent comments for each post.</li>
</ul>
<div class='note'><p>While these column names are optional they are in fact reserved by Active Record. Steer clear of reserved keywords unless you want the extra functionality. For example, “type” is a reserved keyword used to designate a table using Single Table Inheritance. If you are not using <span class="caps">STI</span>, try an analogous keyword like “context”, that may still accurately describe the data you are modeling.</p></div>
<h3 id="creating-active-record-models">3 Creating Active Record Models</h3>
<p>It’s very easy to create Active Record models. All you have to do is to subclass the <tt>ActiveRecord::Base</tt> class and you’re good to go:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Product < ActiveRecord::Base; end
</pre>
</div>
</notextile>
<p>This will create a <tt>Product</tt> model, mapped to a <strong>products</strong> table at the database. By doing this you’ll also have the ability to map the columns of each row in that table with the attributes of the instances of your model. So, suppose that the <strong>products</strong> table was created using an <span class="caps">SQL</span> sentence like:</p>
<notextile>
<div class="code_container">
<pre class="brush: sql; gutter: false; toolbar: false">
CREATE TABLE products (
id int(11) NOT NULL auto_increment,
name varchar(255),
PRIMARY KEY (id)
);
</pre>
</div>
</notextile>
<p>Following the table schema above, you would be able to write code like the following:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
p = Product.new
p.name = "Some Book"
puts p.name # "Some Book"
</pre>
</div>
</notextile>
<h3 id="overriding-the-naming-conventions">4 Overriding the Naming Conventions</h3>
<p>What if you need to follow a different naming convention or need to use your Rails application with a legacy database? No problem, you can easily override the default conventions.</p>
<p>You can use the <tt>ActiveRecord::Base.set_table_name</tt> method to specify the table name that should be used:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Product < ActiveRecord::Base
set_table_name "PRODUCT"
end
</pre>
</div>
</notextile>
<p>If you do so, you will have to define manually the class name that is hosting the fixtures (class_name.yml) using the <tt>set_fixture_class</tt> method in your test definition:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class FunnyJoke < ActiveSupport::TestCase
set_fixture_class :funny_jokes => 'Joke'
fixtures :funny_jokes
...
end
</pre>
</div>
</notextile>
<p>It’s also possible to override the column that should be used as the table’s primary key using the <tt>ActiveRecord::Base.set_primary_key</tt> method:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Product < ActiveRecord::Base
set_primary_key "product_id"
end
</pre>
</div>
</notextile>
<h3 id="reading-and-writing-data">5 Reading and Writing Data</h3>
<p><span class="caps">CRUD</span> is an acronym for the four verbs we use to operate on data: *C*reate, *R*ead, *U*pdate and *D*elete. Active Record automatically creates methods to allow an application to read and manipulate data stored within its tables.</p>
<h4 id="create">5.1 Create</h4>
<p>Active Record objects can be created from a hash, a block or have its attributes manually set after creation. The <em>new</em> method will return a new object while <em>create</em> will return the object and save it to the database.</p>
<p>For example, given a model <tt>User</tt> with attributes of <tt>name</tt> and <tt>occupation</tt>, the <em>create</em> method call will create and save a new record into the database:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
user = User.create(:name => "David", :occupation => "Code Artist")
</pre>
</div>
</notextile>
<p>Using the <em>new</em> method, an object can be created without being saved:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
user = User.new
user.name = "David"
user.occupation = "Code Artist"
</pre>
</div>
</notextile>
<p>A call to <em>user.save</em> will commit the record to the database.</p>
<p>Finally, passing a block to either create or new will return a new User object:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
user = User.new do |u|
u.name = "David"
u.occupation = "Code Artist"
end
</pre>
</div>
</notextile>
<h4 id="read">5.2 Read</h4>
<p>Active Record provides a rich <span class="caps">API</span> for accessing data within a database. Below are a few examples of different data access methods provided by Active Record.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# return all records
users = User.all
</pre>
</div>
</notextile>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# return the first record
user = User.first
</pre>
</div>
</notextile>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# return the first user named David
david = User.find_by_name('David')
</pre>
</div>
</notextile>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
# find all users named David who are Code Artists and sort by created_at in reverse chronological order
users = User.where(:name => 'David', :occupation => 'Code Artist').order('created_at DESC')
</pre>
</div>
</notextile>
<p>You can learn more about querying an Active Record model in the “Active Record Query Interface”:“active_record_querying.html” guide.</p>
<h4 id="update">5.3 Update</h4>
<p>Once an Active Record object has been retrieved, its attributes can be modified and it can be saved to the database.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
user = User.find_by_name('David')
user.name = 'Dave'
user.save
</pre>
</div>
</notextile>
<h4 id="delete">5.4 Delete</h4>
<p>Likewise, once retrieved an Active Record object can be destroyed which removes it from the database.</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
user = User.find_by_name('David')
user.destroy
</pre>
</div>
</notextile>
<h3 id="validations">6 Validations</h3>
<p>Active Record allows you to validate the state of a model before it gets written into the database. There are several methods that you can use to check your models and validate that an attribute value is not empty, is unique and not already in the database, follows a specific format and many more. You can learn more about validations in the <a href="active_record_validations_callbacks.html#validations-overview">Active Record Validations and Callbacks guide</a>.</p>
<h3 id="callbacks">7 Callbacks</h3>
<p>Active Record callbacks allow you to attach code to certain events in the life-cycle of your models. This enables you to add behavior to your models by transparently executing code when those events occur, like when you create a new record, update it, destroy it and so on. You can learn more about callbacks in the <a href="active_record_validations_callbacks.html#callbacks-overview">Active Record Validations and Callbacks guide</a>.</p>
<h3 id="migrations">8 Migrations</h3>
<p>Rails provides a domain-specific language for managing a database schema called migrations. Migrations are stored in files which are executed against any database that Active Record support using rake. Rails keeps track of which files have been committed to the database and provides rollback features. You can learn more about migrations in the <a href="migrations.html">Active Record Migrations guide</a></p>
<h3>Feedback</h3>
<p>
You're encouraged to help in keeping the quality of this guide.
</p>
<p>
If you see any typos or factual errors you are confident to
patch, please clone <a href="https://github.com/lifo/docrails">docrails</a>
and push the change yourself. That branch of Rails has public write access.
Commits are still reviewed, but that happens after you've submitted your
contribution. <a href="https://github.com/lifo/docrails">docrails</a> is
cross-merged with master periodically.
</p>
<p>
You may also find incomplete content, or stuff that is not up to date.
Please do add any missing documentation for master. Check the
<a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a>
for style and conventions.
</p>
<p>
Issues may also be reported in <a href="https://github.com/lifo/docrails/issues">Github</a>.
</p>
<p>And last but not least, any kind of discussion regarding Ruby on Rails
documentation is very welcome in the <a href="http://groups.google.com/group/rubyonrails-docs">rubyonrails-docs mailing list</a>.
</p>
</div>
</div>
</div>
<hr class="hide" />
<div id="footer">
<div class="wrapper">
<p>This work is licensed under a <a href="http://creativecommons.org/licenses/by-sa/3.0/">Creative Commons Attribution-Share Alike 3.0</a> License</p>
<p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p>
</div>
</div>
<script type="text/javascript" src="javascripts/guides.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shCore.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushRuby.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushXml.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushSql.js"></script>
<script type="text/javascript" src="javascripts/syntaxhighlighter/shBrushPlain.js"></script>
<script type="text/javascript">
SyntaxHighlighter.all()
</script>
</body>
</html>