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
/
nested_model_forms.html
387 lines (353 loc) · 18.4 KB
/
nested_model_forms.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
<!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: Rails nested model forms</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>Rails nested model forms</h2>
<p>Creating a form for a model <em>and</em> its associations can become quite tedious. Therefore Rails provides helpers to assist in dealing with the complexities of generating these forms <em>and</em> the required <span class="caps">CRUD</span> operations to create, update, and destroy associations.</p>
<p>In this guide you will:</p>
<ul>
<li>do stuff</li>
</ul>
<div id="subCol">
<h3 class="chapter"><img src="images/chapters_icon.gif" alt="" />Chapters</h3>
<ol class="chapters">
<li><a href="#model-setup">Model setup</a><ul><li><a href="#activerecord-base-model">ActiveRecord::Base model</a></li> <li><a href="#custom-model">Custom model</a></li></ul></li><li><a href="#views">Views</a><ul><li><a href="#controller-code">Controller code</a></li> <li><a href="#form-code">Form code</a></li></ul></li></ol></div>
</div>
</div>
<div id="container">
<div class="wrapper">
<div id="mainCol">
<div class='note'><p>This guide assumes the user knows how to use the <a href="form_helpers.html">Rails form helpers</a> in general. Also, it’s <strong>not</strong> an <span class="caps">API</span> reference. For a complete reference please visit <a href="http://api.rubyonrails.org/">the Rails <span class="caps">API</span> documentation</a>.</p></div>
<h3 id="model-setup">1 Model setup</h3>
<p>To be able to use the nested model functionality in your forms, the model will need to support some basic operations.</p>
<p>First of all, it needs to define a writer method for the attribute that corresponds to the association you are building a nested model form for. The <tt>fields_for</tt> form helper will look for this method to decide whether or not a nested model form should be build.</p>
<p>If the associated object is an array a form builder will be yielded for each object, else only a single form builder will be yielded.</p>
<p>Consider a Person model with an associated Address. When asked to yield a nested FormBuilder for the <tt>:address</tt> attribute, the <tt>fields_for</tt> form helper will look for a method on the Person instance named <tt>address_attributes=</tt>.</p>
<h4 id="activerecord-base-model">1.1 ActiveRecord::Base model</h4>
<p>For an ActiveRecord::Base model and association this writer method is commonly defined with the <tt>accepts_nested_attributes_for</tt> class method:</p>
<h5 id="has_one">1.1.1 has_one</h5>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Person < ActiveRecord::Base
has_one :address
accepts_nested_attributes_for :address
end
</pre>
</div>
</notextile>
<h5 id="belongs_to">1.1.2 belongs_to</h5>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Person < ActiveRecord::Base
belongs_to :firm
accepts_nested_attributes_for :firm
end
</pre>
</div>
</notextile>
<h5 id="has_many-has_and_belongs_to_many">1.1.3 has_many / has_and_belongs_to_many</h5>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Person < ActiveRecord::Base
has_many :projects
accepts_nested_attributes_for :projects
end
</pre>
</div>
</notextile>
<h4 id="custom-model">1.2 Custom model</h4>
<p>As you might have inflected from this explanation, you <em>don’t</em> necessarily need an ActiveRecord::Base model to use this functionality. The following examples are sufficient to enable the nested model form behaviour:</p>
<h5 id="single-associated-object">1.2.1 Single associated object</h5>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Person
def address
Address.new
end
def address_attributes=(attributes)
# ...
end
end
</pre>
</div>
</notextile>
<h5 id="association-collection">1.2.2 Association collection</h5>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class Person
def projects
[Project.new, Project.new]
end
def projects_attributes=(attributes)
# ...
end
end
</pre>
</div>
</notextile>
<div class='note'><p>See (<span class="caps">TODO</span>) in the advanced section for more information on how to deal with the <span class="caps">CRUD</span> operations in your custom model.</p></div>
<h3 id="views">2 Views</h3>
<h4 id="controller-code">2.1 Controller code</h4>
<p>A nested model form will <em>only</em> be build if the associated object(s) exist. This means that for a new model instance you would probably want to build the associated object(s) first.</p>
<p>Consider the following typical RESTful controller which will prepare a new Person instance and its <tt>address</tt> and <tt>projects</tt> associations before rendering the <tt>new</tt> template:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
class PeopleController < ActionController:Base
def new
@person = Person.new
@person.built_address
2.times { @person.projects.build }
end
def create
@person = Person.new(params[:person])
if @person.save
# ...
end
end
end
</pre>
</div>
</notextile>
<div class='note'><p>Obviously the instantiation of the associated object(s) can become tedious and not <span class="caps">DRY</span>, so you might want to move that into the model itself. ActiveRecord::Base provides an <tt>after_initialize</tt> callback which is a good way to refactor this.</p></div>
<h4 id="form-code">2.2 Form code</h4>
<p>Now that you have a model instance, with the appropriate methods and associated object(s), you can start building the nested model form.</p>
<h5 id="standard-form">2.2.1 Standard form</h5>
<p>Start out with a regular RESTful form:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_for @person do |f| %>
<%= f.text_field :name %>
<% end %>
</pre>
</div>
</notextile>
<p>This will generate the following html:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form action="/people" class="new_person" id="new_person" method="post">
<input id="person_name" name="person[name]" size="30" type="text" />
</form>
</pre>
</div>
</notextile>
<h5 id="nested-form-for-a-single-associated-object">2.2.2 Nested form for a single associated object</h5>
<p>Now add a nested form for the <tt>address</tt> association:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_for @person do |f| %>
<%= f.text_field :name %>
<%= f.fields_for :address do |af| %>
<%= f.text_field :street %>
<% end %>
<% end %>
</pre>
</div>
</notextile>
<p>This generates:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form action="/people" class="new_person" id="new_person" method="post">
<input id="person_name" name="person[name]" size="30" type="text" />
<input id="person_address_attributes_street" name="person[address_attributes][street]" size="30" type="text" />
</form>
</pre>
</div>
</notextile>
<p>Notice that <tt>fields_for</tt> recognized the <tt>address</tt> as an association for which a nested model form should be build by the way it has namespaced the <tt>name</tt> attribute.</p>
<p>When this form is posted the Rails parameter parser will construct a hash like the following:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{
"person" => {
"name" => "Eloy Duran",
"address_attributes" => {
"street" => "Nieuwe Prinsengracht"
}
}
}
</pre>
</div>
</notextile>
<p>That’s it. The controller will simply pass this hash on to the model from the <tt>create</tt> action. The model will then handle building the <tt>address</tt> association for you and automatically save it when the parent (<tt>person</tt>) is saved.</p>
<h5 id="nested-form-for-a-collection-of-associated-objects">2.2.3 Nested form for a collection of associated objects</h5>
<p>The form code for an association collection is pretty similar to that of a single associated object:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; html-script: true; gutter: false; toolbar: false">
<%= form_for @person do |f| %>
<%= f.text_field :name %>
<%= f.fields_for :projects do |pf| %>
<%= f.text_field :name %>
<% end %>
<% end %>
</pre>
</div>
</notextile>
<p>Which generates:</p>
<notextile>
<div class="code_container">
<pre class="brush: xml; gutter: false; toolbar: false">
<form action="/people" class="new_person" id="new_person" method="post">
<input id="person_name" name="person[name]" size="30" type="text" />
<input id="person_projects_attributes_0_name" name="person[projects_attributes][0][name]" size="30" type="text" />
<input id="person_projects_attributes_1_name" name="person[projects_attributes][1][name]" size="30" type="text" />
</form>
</pre>
</div>
</notextile>
<p>As you can see it has generated 2 <tt>project name</tt> inputs, one for each new <tt>project</tt> that’s build in the controllers <tt>new</tt> action. Only this time the <tt>name</tt> attribute of the input contains a digit as an extra namespace. This will be parsed by the Rails parameter parser as:</p>
<notextile>
<div class="code_container">
<pre class="brush: ruby; gutter: false; toolbar: false">
{
"person" => {
"name" => "Eloy Duran",
"projects_attributes" => {
"0" => { "name" => "Project 1" },
"1" => { "name" => "Project 2" }
}
}
}
</pre>
</div>
</notextile>
<p>You can basically see the <tt>projects_attributes</tt> hash as an array of attribute hashes. One for each model instance.</p>
<div class='note'><p>The reason that <tt>fields_for</tt> constructed a form which would result in a hash instead of an array is that it won’t work for any forms nested deeper than one level deep.</p></div>
<div class='info'><p>You <em>can</em> however pass an array to the writer method generated by <tt>accepts_nested_attributes_for</tt> if you’re using plain Ruby or some other <span class="caps">API</span> access. See (<span class="caps">TODO</span>) for more info and example.</p></div>
<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>