rails 4.2.6.rc1 → 5.2.8.1

Sign up to get free protection for your applications and to get access to all the features.

Potentially problematic release.


This version of rails might be problematic. Click here for more details.

Files changed (218) hide show
  1. checksums.yaml +5 -5
  2. data/README.md +24 -12
  3. metadata +54 -248
  4. data/guides/CHANGELOG.md +0 -73
  5. data/guides/Rakefile +0 -79
  6. data/guides/assets/images/akshaysurve.jpg +0 -0
  7. data/guides/assets/images/belongs_to.png +0 -0
  8. data/guides/assets/images/book_icon.gif +0 -0
  9. data/guides/assets/images/bullet.gif +0 -0
  10. data/guides/assets/images/chapters_icon.gif +0 -0
  11. data/guides/assets/images/check_bullet.gif +0 -0
  12. data/guides/assets/images/credits_pic_blank.gif +0 -0
  13. data/guides/assets/images/csrf.png +0 -0
  14. data/guides/assets/images/edge_badge.png +0 -0
  15. data/guides/assets/images/favicon.ico +0 -0
  16. data/guides/assets/images/feature_tile.gif +0 -0
  17. data/guides/assets/images/footer_tile.gif +0 -0
  18. data/guides/assets/images/fxn.png +0 -0
  19. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  20. data/guides/assets/images/getting_started/challenge.png +0 -0
  21. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  22. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  23. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  24. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  25. data/guides/assets/images/getting_started/new_article.png +0 -0
  26. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  27. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  28. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  29. data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
  30. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  31. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  32. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  33. data/guides/assets/images/grey_bullet.gif +0 -0
  34. data/guides/assets/images/habtm.png +0 -0
  35. data/guides/assets/images/has_many.png +0 -0
  36. data/guides/assets/images/has_many_through.png +0 -0
  37. data/guides/assets/images/has_one.png +0 -0
  38. data/guides/assets/images/has_one_through.png +0 -0
  39. data/guides/assets/images/header_backdrop.png +0 -0
  40. data/guides/assets/images/header_tile.gif +0 -0
  41. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  42. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  43. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  44. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  45. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  46. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  47. data/guides/assets/images/icons/README +0 -5
  48. data/guides/assets/images/icons/callouts/1.png +0 -0
  49. data/guides/assets/images/icons/callouts/10.png +0 -0
  50. data/guides/assets/images/icons/callouts/11.png +0 -0
  51. data/guides/assets/images/icons/callouts/12.png +0 -0
  52. data/guides/assets/images/icons/callouts/13.png +0 -0
  53. data/guides/assets/images/icons/callouts/14.png +0 -0
  54. data/guides/assets/images/icons/callouts/15.png +0 -0
  55. data/guides/assets/images/icons/callouts/2.png +0 -0
  56. data/guides/assets/images/icons/callouts/3.png +0 -0
  57. data/guides/assets/images/icons/callouts/4.png +0 -0
  58. data/guides/assets/images/icons/callouts/5.png +0 -0
  59. data/guides/assets/images/icons/callouts/6.png +0 -0
  60. data/guides/assets/images/icons/callouts/7.png +0 -0
  61. data/guides/assets/images/icons/callouts/8.png +0 -0
  62. data/guides/assets/images/icons/callouts/9.png +0 -0
  63. data/guides/assets/images/icons/caution.png +0 -0
  64. data/guides/assets/images/icons/example.png +0 -0
  65. data/guides/assets/images/icons/home.png +0 -0
  66. data/guides/assets/images/icons/important.png +0 -0
  67. data/guides/assets/images/icons/next.png +0 -0
  68. data/guides/assets/images/icons/note.png +0 -0
  69. data/guides/assets/images/icons/prev.png +0 -0
  70. data/guides/assets/images/icons/tip.png +0 -0
  71. data/guides/assets/images/icons/up.png +0 -0
  72. data/guides/assets/images/icons/warning.png +0 -0
  73. data/guides/assets/images/nav_arrow.gif +0 -0
  74. data/guides/assets/images/oscardelben.jpg +0 -0
  75. data/guides/assets/images/polymorphic.png +0 -0
  76. data/guides/assets/images/radar.png +0 -0
  77. data/guides/assets/images/rails4_features.png +0 -0
  78. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  79. data/guides/assets/images/rails_guides_logo.gif +0 -0
  80. data/guides/assets/images/rails_logo_remix.gif +0 -0
  81. data/guides/assets/images/session_fixation.png +0 -0
  82. data/guides/assets/images/tab_grey.gif +0 -0
  83. data/guides/assets/images/tab_info.gif +0 -0
  84. data/guides/assets/images/tab_note.gif +0 -0
  85. data/guides/assets/images/tab_red.gif +0 -0
  86. data/guides/assets/images/tab_yellow.gif +0 -0
  87. data/guides/assets/images/tab_yellow.png +0 -0
  88. data/guides/assets/images/vijaydev.jpg +0 -0
  89. data/guides/assets/javascripts/guides.js +0 -59
  90. data/guides/assets/javascripts/jquery.min.js +0 -4
  91. data/guides/assets/javascripts/responsive-tables.js +0 -43
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +0 -59
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +0 -75
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +0 -59
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +0 -65
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +0 -100
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +0 -97
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +0 -91
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +0 -55
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +0 -41
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +0 -52
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +0 -67
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +0 -52
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +0 -57
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +0 -58
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +0 -72
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +0 -88
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +0 -33
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +0 -74
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +0 -64
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +0 -55
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +0 -94
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +0 -51
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +0 -66
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +0 -56
  116. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +0 -69
  117. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +0 -17
  118. data/guides/assets/stylesheets/fixes.css +0 -16
  119. data/guides/assets/stylesheets/kindle.css +0 -11
  120. data/guides/assets/stylesheets/main.css +0 -713
  121. data/guides/assets/stylesheets/print.css +0 -52
  122. data/guides/assets/stylesheets/reset.css +0 -43
  123. data/guides/assets/stylesheets/responsive-tables.css +0 -50
  124. data/guides/assets/stylesheets/style.css +0 -13
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +0 -226
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +0 -328
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +0 -331
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +0 -339
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +0 -324
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +0 -328
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +0 -324
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +0 -324
  133. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +0 -324
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +0 -117
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +0 -120
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +0 -128
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +0 -113
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +0 -117
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +0 -113
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +0 -113
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +0 -113
  142. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +0 -116
  143. data/guides/bug_report_templates/action_controller_gem.rb +0 -47
  144. data/guides/bug_report_templates/action_controller_master.rb +0 -54
  145. data/guides/bug_report_templates/active_record_gem.rb +0 -40
  146. data/guides/bug_report_templates/active_record_master.rb +0 -49
  147. data/guides/bug_report_templates/generic_gem.rb +0 -15
  148. data/guides/bug_report_templates/generic_master.rb +0 -26
  149. data/guides/rails_guides/generator.rb +0 -248
  150. data/guides/rails_guides/helpers.rb +0 -53
  151. data/guides/rails_guides/indexer.rb +0 -68
  152. data/guides/rails_guides/kindle.rb +0 -119
  153. data/guides/rails_guides/levenshtein.rb +0 -37
  154. data/guides/rails_guides/markdown/renderer.rb +0 -82
  155. data/guides/rails_guides/markdown.rb +0 -167
  156. data/guides/rails_guides.rb +0 -63
  157. data/guides/source/2_2_release_notes.md +0 -435
  158. data/guides/source/2_3_release_notes.md +0 -621
  159. data/guides/source/3_0_release_notes.md +0 -611
  160. data/guides/source/3_1_release_notes.md +0 -559
  161. data/guides/source/3_2_release_notes.md +0 -568
  162. data/guides/source/4_0_release_notes.md +0 -279
  163. data/guides/source/4_1_release_notes.md +0 -730
  164. data/guides/source/4_2_release_notes.md +0 -877
  165. data/guides/source/_license.html.erb +0 -2
  166. data/guides/source/_welcome.html.erb +0 -23
  167. data/guides/source/action_controller_overview.md +0 -1192
  168. data/guides/source/action_mailer_basics.md +0 -757
  169. data/guides/source/action_view_overview.md +0 -1561
  170. data/guides/source/active_job_basics.md +0 -339
  171. data/guides/source/active_model_basics.md +0 -554
  172. data/guides/source/active_record_basics.md +0 -374
  173. data/guides/source/active_record_callbacks.md +0 -413
  174. data/guides/source/active_record_migrations.md +0 -1018
  175. data/guides/source/active_record_postgresql.md +0 -433
  176. data/guides/source/active_record_querying.md +0 -1781
  177. data/guides/source/active_record_validations.md +0 -1179
  178. data/guides/source/active_support_core_extensions.md +0 -3857
  179. data/guides/source/active_support_instrumentation.md +0 -488
  180. data/guides/source/api_documentation_guidelines.md +0 -361
  181. data/guides/source/asset_pipeline.md +0 -1304
  182. data/guides/source/association_basics.md +0 -2245
  183. data/guides/source/autoloading_and_reloading_constants.md +0 -1311
  184. data/guides/source/caching_with_rails.md +0 -379
  185. data/guides/source/command_line.md +0 -625
  186. data/guides/source/configuring.md +0 -1072
  187. data/guides/source/contributing_to_ruby_on_rails.md +0 -628
  188. data/guides/source/credits.html.erb +0 -80
  189. data/guides/source/debugging_rails_applications.md +0 -861
  190. data/guides/source/development_dependencies_install.md +0 -289
  191. data/guides/source/documents.yaml +0 -205
  192. data/guides/source/engines.md +0 -1412
  193. data/guides/source/form_helpers.md +0 -1024
  194. data/guides/source/generators.md +0 -676
  195. data/guides/source/getting_started.md +0 -2086
  196. data/guides/source/i18n.md +0 -1087
  197. data/guides/source/index.html.erb +0 -28
  198. data/guides/source/initialization.md +0 -704
  199. data/guides/source/kindle/copyright.html.erb +0 -1
  200. data/guides/source/kindle/layout.html.erb +0 -27
  201. data/guides/source/kindle/rails_guides.opf.erb +0 -52
  202. data/guides/source/kindle/toc.html.erb +0 -24
  203. data/guides/source/kindle/toc.ncx.erb +0 -64
  204. data/guides/source/kindle/welcome.html.erb +0 -5
  205. data/guides/source/layout.html.erb +0 -140
  206. data/guides/source/layouts_and_rendering.md +0 -1227
  207. data/guides/source/maintenance_policy.md +0 -78
  208. data/guides/source/nested_model_forms.md +0 -228
  209. data/guides/source/plugins.md +0 -444
  210. data/guides/source/rails_application_templates.md +0 -266
  211. data/guides/source/rails_on_rack.md +0 -336
  212. data/guides/source/routing.md +0 -1155
  213. data/guides/source/ruby_on_rails_guides_guidelines.md +0 -127
  214. data/guides/source/security.md +0 -1024
  215. data/guides/source/testing.md +0 -1132
  216. data/guides/source/upgrading_ruby_on_rails.md +0 -1186
  217. data/guides/source/working_with_javascript_in_rails.md +0 -407
  218. data/guides/w3c_validator.rb +0 -97
@@ -1,1227 +0,0 @@
1
- Layouts and Rendering in Rails
2
- ==============================
3
-
4
- This guide covers the basic layout features of Action Controller and Action View.
5
-
6
- After reading this guide, you will know:
7
-
8
- * How to use the various rendering methods built into Rails.
9
- * How to create layouts with multiple content sections.
10
- * How to use partials to DRY up your views.
11
- * How to use nested layouts (sub-templates).
12
-
13
- --------------------------------------------------------------------------------
14
-
15
- Overview: How the Pieces Fit Together
16
- -------------------------------------
17
-
18
- This guide focuses on the interaction between Controller and View in the Model-View-Controller triangle. As you know, the Controller is responsible for orchestrating the whole process of handling a request in Rails, though it normally hands off any heavy code to the Model. But then, when it's time to send a response back to the user, the Controller hands things off to the View. It's that handoff that is the subject of this guide.
19
-
20
- In broad strokes, this involves deciding what should be sent as the response and calling an appropriate method to create that response. If the response is a full-blown view, Rails also does some extra work to wrap the view in a layout and possibly to pull in partial views. You'll see all of those paths later in this guide.
21
-
22
- Creating Responses
23
- ------------------
24
-
25
- From the controller's point of view, there are three ways to create an HTTP response:
26
-
27
- * Call `render` to create a full response to send back to the browser
28
- * Call `redirect_to` to send an HTTP redirect status code to the browser
29
- * Call `head` to create a response consisting solely of HTTP headers to send back to the browser
30
-
31
- ### Rendering by Default: Convention Over Configuration in Action
32
-
33
- You've heard that Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your `BooksController` class:
34
-
35
- ```ruby
36
- class BooksController < ApplicationController
37
- end
38
- ```
39
-
40
- And the following in your routes file:
41
-
42
- ```ruby
43
- resources :books
44
- ```
45
-
46
- And you have a view file `app/views/books/index.html.erb`:
47
-
48
- ```html+erb
49
- <h1>Books are coming soon!</h1>
50
- ```
51
-
52
- Rails will automatically render `app/views/books/index.html.erb` when you navigate to `/books` and you will see "Books are coming soon!" on your screen.
53
-
54
- However a coming soon screen is only minimally useful, so you will soon create your `Book` model and add the index action to `BooksController`:
55
-
56
- ```ruby
57
- class BooksController < ApplicationController
58
- def index
59
- @books = Book.all
60
- end
61
- end
62
- ```
63
-
64
- Note that we don't have explicit render at the end of the index action in accordance with "convention over configuration" principle. The rule is that if you do not explicitly render something at the end of a controller action, Rails will automatically look for the `action_name.html.erb` template in the controller's view path and render it. So in this case, Rails will render the `app/views/books/index.html.erb` file.
65
-
66
- If we want to display the properties of all the books in our view, we can do so with an ERB template like this:
67
-
68
- ```html+erb
69
- <h1>Listing Books</h1>
70
-
71
- <table>
72
- <tr>
73
- <th>Title</th>
74
- <th>Summary</th>
75
- <th></th>
76
- <th></th>
77
- <th></th>
78
- </tr>
79
-
80
- <% @books.each do |book| %>
81
- <tr>
82
- <td><%= book.title %></td>
83
- <td><%= book.content %></td>
84
- <td><%= link_to "Show", book %></td>
85
- <td><%= link_to "Edit", edit_book_path(book) %></td>
86
- <td><%= link_to "Remove", book, method: :delete, data: { confirm: "Are you sure?" } %></td>
87
- </tr>
88
- <% end %>
89
- </table>
90
-
91
- <br>
92
-
93
- <%= link_to "New book", new_book_path %>
94
- ```
95
-
96
- NOTE: The actual rendering is done by subclasses of `ActionView::TemplateHandlers`. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler. Beginning with Rails 2, the standard extensions are `.erb` for ERB (HTML with embedded Ruby), and `.builder` for Builder (XML generator).
97
-
98
- ### Using `render`
99
-
100
- In most cases, the `ActionController::Base#render` method does the heavy lifting of rendering your application's content for use by a browser. There are a variety of ways to customize the behavior of `render`. You can render the default view for a Rails template, or a specific template, or a file, or inline code, or nothing at all. You can render text, JSON, or XML. You can specify the content type or HTTP status of the rendered response as well.
101
-
102
- TIP: If you want to see the exact results of a call to `render` without needing to inspect it in a browser, you can call `render_to_string`. This method takes exactly the same options as `render`, but it returns a string instead of sending a response back to the browser.
103
-
104
- #### Rendering Nothing
105
-
106
- Perhaps the simplest thing you can do with `render` is to render nothing at all:
107
-
108
- ```ruby
109
- render nothing: true
110
- ```
111
-
112
- If you look at the response for this using cURL, you will see the following:
113
-
114
- ```bash
115
- $ curl -i 127.0.0.1:3000/books
116
- HTTP/1.1 200 OK
117
- Connection: close
118
- Date: Sun, 24 Jan 2010 09:25:18 GMT
119
- Transfer-Encoding: chunked
120
- Content-Type: */*; charset=utf-8
121
- X-Runtime: 0.014297
122
- Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
123
- Cache-Control: no-cache
124
-
125
- $
126
- ```
127
-
128
- We see there is an empty response (no data after the `Cache-Control` line), but the request was successful because Rails has set the response to 200 OK. You can set the `:status` option on render to change this response. Rendering nothing can be useful for Ajax requests where all you want to send back to the browser is an acknowledgment that the request was completed.
129
-
130
- TIP: You should probably be using the `head` method, discussed later in this guide, instead of `render :nothing`. This provides additional flexibility and makes it explicit that you're only generating HTTP headers.
131
-
132
- #### Rendering an Action's View
133
-
134
- If you want to render the view that corresponds to a different template within the same controller, you can use `render` with the name of the view:
135
-
136
- ```ruby
137
- def update
138
- @book = Book.find(params[:id])
139
- if @book.update(book_params)
140
- redirect_to(@book)
141
- else
142
- render "edit"
143
- end
144
- end
145
- ```
146
-
147
- If the call to `update` fails, calling the `update` action in this controller will render the `edit.html.erb` template belonging to the same controller.
148
-
149
- If you prefer, you can use a symbol instead of a string to specify the action to render:
150
-
151
- ```ruby
152
- def update
153
- @book = Book.find(params[:id])
154
- if @book.update(book_params)
155
- redirect_to(@book)
156
- else
157
- render :edit
158
- end
159
- end
160
- ```
161
-
162
- #### Rendering an Action's Template from Another Controller
163
-
164
- What if you want to render a template from an entirely different controller from the one that contains the action code? You can also do that with `render`, which accepts the full path (relative to `app/views`) of the template to render. For example, if you're running code in an `AdminProductsController` that lives in `app/controllers/admin`, you can render the results of an action to a template in `app/views/products` this way:
165
-
166
- ```ruby
167
- render "products/show"
168
- ```
169
-
170
- Rails knows that this view belongs to a different controller because of the embedded slash character in the string. If you want to be explicit, you can use the `:template` option (which was required on Rails 2.2 and earlier):
171
-
172
- ```ruby
173
- render template: "products/show"
174
- ```
175
-
176
- #### Rendering an Arbitrary File
177
-
178
- The `render` method can also use a view that's entirely outside of your application (perhaps you're sharing views between two Rails applications):
179
-
180
- ```ruby
181
- render "/u/apps/warehouse_app/current/app/views/products/show"
182
- ```
183
-
184
- Rails determines that this is a file render because of the leading slash character. To be explicit, you can use the `:file` option (which was required on Rails 2.2 and earlier):
185
-
186
- ```ruby
187
- render file: "/u/apps/warehouse_app/current/app/views/products/show"
188
- ```
189
-
190
- The `:file` option takes an absolute file-system path. Of course, you need to have rights to the view that you're using to render the content.
191
-
192
- NOTE: By default, the file is rendered using the current layout.
193
-
194
- TIP: If you're running Rails on Microsoft Windows, you should use the `:file` option to render a file, because Windows filenames do not have the same format as Unix filenames.
195
-
196
- #### Wrapping it up
197
-
198
- The above three ways of rendering (rendering another template within the controller, rendering a template within another controller and rendering an arbitrary file on the file system) are actually variants of the same action.
199
-
200
- In fact, in the BooksController class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the `edit.html.erb` template in the `views/books` directory:
201
-
202
- ```ruby
203
- render :edit
204
- render action: :edit
205
- render "edit"
206
- render "edit.html.erb"
207
- render action: "edit"
208
- render action: "edit.html.erb"
209
- render "books/edit"
210
- render "books/edit.html.erb"
211
- render template: "books/edit"
212
- render template: "books/edit.html.erb"
213
- render "/path/to/rails/app/views/books/edit"
214
- render "/path/to/rails/app/views/books/edit.html.erb"
215
- render file: "/path/to/rails/app/views/books/edit"
216
- render file: "/path/to/rails/app/views/books/edit.html.erb"
217
- ```
218
-
219
- Which one you use is really a matter of style and convention, but the rule of thumb is to use the simplest one that makes sense for the code you are writing.
220
-
221
- #### Using `render` with `:inline`
222
-
223
- The `render` method can do without a view completely, if you're willing to use the `:inline` option to supply ERB as part of the method call. This is perfectly valid:
224
-
225
- ```ruby
226
- render inline: "<% products.each do |p| %><p><%= p.name %></p><% end %>"
227
- ```
228
-
229
- WARNING: There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead.
230
-
231
- By default, inline rendering uses ERB. You can force it to use Builder instead with the `:type` option:
232
-
233
- ```ruby
234
- render inline: "xml.p {'Horrid coding practice!'}", type: :builder
235
- ```
236
-
237
- #### Rendering Text
238
-
239
- You can send plain text - with no markup at all - back to the browser by using
240
- the `:plain` option to `render`:
241
-
242
- ```ruby
243
- render plain: "OK"
244
- ```
245
-
246
- TIP: Rendering pure text is most useful when you're responding to Ajax or web
247
- service requests that are expecting something other than proper HTML.
248
-
249
- NOTE: By default, if you use the `:plain` option, the text is rendered without
250
- using the current layout. If you want Rails to put the text into the current
251
- layout, you need to add the `layout: true` option and use the `.txt.erb`
252
- extension for the layout file.
253
-
254
- #### Rendering HTML
255
-
256
- You can send a HTML string back to the browser by using the `:html` option to
257
- `render`:
258
-
259
- ```ruby
260
- render html: "<strong>Not Found</strong>".html_safe
261
- ```
262
-
263
- TIP: This is useful when you're rendering a small snippet of HTML code.
264
- However, you might want to consider moving it to a template file if the markup
265
- is complex.
266
-
267
- NOTE: This option will escape HTML entities if the string is not HTML safe.
268
-
269
- #### Rendering JSON
270
-
271
- JSON is a JavaScript data format used by many Ajax libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:
272
-
273
- ```ruby
274
- render json: @product
275
- ```
276
-
277
- TIP: You don't need to call `to_json` on the object that you want to render. If you use the `:json` option, `render` will automatically call `to_json` for you.
278
-
279
- #### Rendering XML
280
-
281
- Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:
282
-
283
- ```ruby
284
- render xml: @product
285
- ```
286
-
287
- TIP: You don't need to call `to_xml` on the object that you want to render. If you use the `:xml` option, `render` will automatically call `to_xml` for you.
288
-
289
- #### Rendering Vanilla JavaScript
290
-
291
- Rails can render vanilla JavaScript:
292
-
293
- ```ruby
294
- render js: "alert('Hello Rails');"
295
- ```
296
-
297
- This will send the supplied string to the browser with a MIME type of `text/javascript`.
298
-
299
- #### Rendering raw body
300
-
301
- You can send a raw content back to the browser, without setting any content
302
- type, by using the `:body` option to `render`:
303
-
304
- ```ruby
305
- render body: "raw"
306
- ```
307
-
308
- TIP: This option should be used only if you don't care about the content type of
309
- the response. Using `:plain` or `:html` might be more appropriate in most of the
310
- time.
311
-
312
- NOTE: Unless overridden, your response returned from this render option will be
313
- `text/html`, as that is the default content type of Action Dispatch response.
314
-
315
- #### Options for `render`
316
-
317
- Calls to the `render` method generally accept four options:
318
-
319
- * `:content_type`
320
- * `:layout`
321
- * `:location`
322
- * `:status`
323
-
324
- ##### The `:content_type` Option
325
-
326
- By default, Rails will serve the results of a rendering operation with the MIME content-type of `text/html` (or `application/json` if you use the `:json` option, or `application/xml` for the `:xml` option.). There are times when you might like to change this, and you can do so by setting the `:content_type` option:
327
-
328
- ```ruby
329
- render file: filename, content_type: "application/rss"
330
- ```
331
-
332
- ##### The `:layout` Option
333
-
334
- With most of the options to `render`, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.
335
-
336
- You can use the `:layout` option to tell Rails to use a specific file as the layout for the current action:
337
-
338
- ```ruby
339
- render layout: "special_layout"
340
- ```
341
-
342
- You can also tell Rails to render with no layout at all:
343
-
344
- ```ruby
345
- render layout: false
346
- ```
347
-
348
- ##### The `:location` Option
349
-
350
- You can use the `:location` option to set the HTTP `Location` header:
351
-
352
- ```ruby
353
- render xml: photo, location: photo_url(photo)
354
- ```
355
-
356
- ##### The `:status` Option
357
-
358
- Rails will automatically generate a response with the correct HTTP status code (in most cases, this is `200 OK`). You can use the `:status` option to change this:
359
-
360
- ```ruby
361
- render status: 500
362
- render status: :forbidden
363
- ```
364
-
365
- Rails understands both numeric status codes and the corresponding symbols shown below.
366
-
367
- | Response Class | HTTP Status Code | Symbol |
368
- | ------------------- | ---------------- | -------------------------------- |
369
- | **Informational** | 100 | :continue |
370
- | | 101 | :switching_protocols |
371
- | | 102 | :processing |
372
- | **Success** | 200 | :ok |
373
- | | 201 | :created |
374
- | | 202 | :accepted |
375
- | | 203 | :non_authoritative_information |
376
- | | 204 | :no_content |
377
- | | 205 | :reset_content |
378
- | | 206 | :partial_content |
379
- | | 207 | :multi_status |
380
- | | 208 | :already_reported |
381
- | | 226 | :im_used |
382
- | **Redirection** | 300 | :multiple_choices |
383
- | | 301 | :moved_permanently |
384
- | | 302 | :found |
385
- | | 303 | :see_other |
386
- | | 304 | :not_modified |
387
- | | 305 | :use_proxy |
388
- | | 306 | :reserved |
389
- | | 307 | :temporary_redirect |
390
- | | 308 | :permanent_redirect |
391
- | **Client Error** | 400 | :bad_request |
392
- | | 401 | :unauthorized |
393
- | | 402 | :payment_required |
394
- | | 403 | :forbidden |
395
- | | 404 | :not_found |
396
- | | 405 | :method_not_allowed |
397
- | | 406 | :not_acceptable |
398
- | | 407 | :proxy_authentication_required |
399
- | | 408 | :request_timeout |
400
- | | 409 | :conflict |
401
- | | 410 | :gone |
402
- | | 411 | :length_required |
403
- | | 412 | :precondition_failed |
404
- | | 413 | :request_entity_too_large |
405
- | | 414 | :request_uri_too_long |
406
- | | 415 | :unsupported_media_type |
407
- | | 416 | :requested_range_not_satisfiable |
408
- | | 417 | :expectation_failed |
409
- | | 422 | :unprocessable_entity |
410
- | | 423 | :locked |
411
- | | 424 | :failed_dependency |
412
- | | 426 | :upgrade_required |
413
- | | 428 | :precondition_required |
414
- | | 429 | :too_many_requests |
415
- | | 431 | :request_header_fields_too_large |
416
- | **Server Error** | 500 | :internal_server_error |
417
- | | 501 | :not_implemented |
418
- | | 502 | :bad_gateway |
419
- | | 503 | :service_unavailable |
420
- | | 504 | :gateway_timeout |
421
- | | 505 | :http_version_not_supported |
422
- | | 506 | :variant_also_negotiates |
423
- | | 507 | :insufficient_storage |
424
- | | 508 | :loop_detected |
425
- | | 510 | :not_extended |
426
- | | 511 | :network_authentication_required |
427
-
428
- #### Finding Layouts
429
-
430
- To find the current layout, Rails first looks for a file in `app/views/layouts` with the same base name as the controller. For example, rendering actions from the `PhotosController` class will use `app/views/layouts/photos.html.erb` (or `app/views/layouts/photos.builder`). If there is no such controller-specific layout, Rails will use `app/views/layouts/application.html.erb` or `app/views/layouts/application.builder`. If there is no `.erb` layout, Rails will use a `.builder` layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.
431
-
432
- ##### Specifying Layouts for Controllers
433
-
434
- You can override the default layout conventions in your controllers by using the `layout` declaration. For example:
435
-
436
- ```ruby
437
- class ProductsController < ApplicationController
438
- layout "inventory"
439
- #...
440
- end
441
- ```
442
-
443
- With this declaration, all of the views rendered by the `ProductsController` will use `app/views/layouts/inventory.html.erb` as their layout.
444
-
445
- To assign a specific layout for the entire application, use a `layout` declaration in your `ApplicationController` class:
446
-
447
- ```ruby
448
- class ApplicationController < ActionController::Base
449
- layout "main"
450
- #...
451
- end
452
- ```
453
-
454
- With this declaration, all of the views in the entire application will use `app/views/layouts/main.html.erb` for their layout.
455
-
456
- ##### Choosing Layouts at Runtime
457
-
458
- You can use a symbol to defer the choice of layout until a request is processed:
459
-
460
- ```ruby
461
- class ProductsController < ApplicationController
462
- layout :products_layout
463
-
464
- def show
465
- @product = Product.find(params[:id])
466
- end
467
-
468
- private
469
- def products_layout
470
- @current_user.special? ? "special" : "products"
471
- end
472
-
473
- end
474
- ```
475
-
476
- Now, if the current user is a special user, they'll get a special layout when viewing a product.
477
-
478
- You can even use an inline method, such as a Proc, to determine the layout. For example, if you pass a Proc object, the block you give the Proc will be given the `controller` instance, so the layout can be determined based on the current request:
479
-
480
- ```ruby
481
- class ProductsController < ApplicationController
482
- layout Proc.new { |controller| controller.request.xhr? ? "popup" : "application" }
483
- end
484
- ```
485
-
486
- ##### Conditional Layouts
487
-
488
- Layouts specified at the controller level support the `:only` and `:except` options. These options take either a method name, or an array of method names, corresponding to method names within the controller:
489
-
490
- ```ruby
491
- class ProductsController < ApplicationController
492
- layout "product", except: [:index, :rss]
493
- end
494
- ```
495
-
496
- With this declaration, the `product` layout would be used for everything but the `rss` and `index` methods.
497
-
498
- ##### Layout Inheritance
499
-
500
- Layout declarations cascade downward in the hierarchy, and more specific layout declarations always override more general ones. For example:
501
-
502
- * `application_controller.rb`
503
-
504
- ```ruby
505
- class ApplicationController < ActionController::Base
506
- layout "main"
507
- end
508
- ```
509
-
510
- * `articles_controller.rb`
511
-
512
- ```ruby
513
- class ArticlesController < ApplicationController
514
- end
515
- ```
516
-
517
- * `special_articles_controller.rb`
518
-
519
- ```ruby
520
- class SpecialArticlesController < ArticlesController
521
- layout "special"
522
- end
523
- ```
524
-
525
- * `old_articles_controller.rb`
526
-
527
- ```ruby
528
- class OldArticlesController < SpecialArticlesController
529
- layout false
530
-
531
- def show
532
- @article = Article.find(params[:id])
533
- end
534
-
535
- def index
536
- @old_articles = Article.older
537
- render layout: "old"
538
- end
539
- # ...
540
- end
541
- ```
542
-
543
- In this application:
544
-
545
- * In general, views will be rendered in the `main` layout
546
- * `ArticlesController#index` will use the `main` layout
547
- * `SpecialArticlesController#index` will use the `special` layout
548
- * `OldArticlesController#show` will use no layout at all
549
- * `OldArticlesController#index` will use the `old` layout
550
-
551
- #### Avoiding Double Render Errors
552
-
553
- Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that `render` works.
554
-
555
- For example, here's some code that will trigger this error:
556
-
557
- ```ruby
558
- def show
559
- @book = Book.find(params[:id])
560
- if @book.special?
561
- render action: "special_show"
562
- end
563
- render action: "regular_show"
564
- end
565
- ```
566
-
567
- If `@book.special?` evaluates to `true`, Rails will start the rendering process to dump the `@book` variable into the `special_show` view. But this will _not_ stop the rest of the code in the `show` action from running, and when Rails hits the end of the action, it will start to render the `regular_show` view - and throw an error. The solution is simple: make sure that you have only one call to `render` or `redirect` in a single code path. One thing that can help is `and return`. Here's a patched version of the method:
568
-
569
- ```ruby
570
- def show
571
- @book = Book.find(params[:id])
572
- if @book.special?
573
- render action: "special_show" and return
574
- end
575
- render action: "regular_show"
576
- end
577
- ```
578
-
579
- Make sure to use `and return` instead of `&& return` because `&& return` will not work due to the operator precedence in the Ruby Language.
580
-
581
- Note that the implicit render done by ActionController detects if `render` has been called, so the following will work without errors:
582
-
583
- ```ruby
584
- def show
585
- @book = Book.find(params[:id])
586
- if @book.special?
587
- render action: "special_show"
588
- end
589
- end
590
- ```
591
-
592
- This will render a book with `special?` set with the `special_show` template, while other books will render with the default `show` template.
593
-
594
- ### Using `redirect_to`
595
-
596
- Another way to handle returning responses to an HTTP request is with `redirect_to`. As you've seen, `render` tells Rails which view (or other asset) to use in constructing a response. The `redirect_to` method does something completely different: it tells the browser to send a new request for a different URL. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call:
597
-
598
- ```ruby
599
- redirect_to photos_url
600
- ```
601
-
602
- You can use `redirect_to` with any arguments that you could use with `link_to` or `url_for`. There's also a special redirect that sends the user back to the page they just came from:
603
-
604
- ```ruby
605
- redirect_to :back
606
- ```
607
-
608
- #### Getting a Different Redirect Status Code
609
-
610
- Rails uses HTTP status code 302, a temporary redirect, when you call `redirect_to`. If you'd like to use a different status code, perhaps 301, a permanent redirect, you can use the `:status` option:
611
-
612
- ```ruby
613
- redirect_to photos_path, status: 301
614
- ```
615
-
616
- Just like the `:status` option for `render`, `:status` for `redirect_to` accepts both numeric and symbolic header designations.
617
-
618
- #### The Difference Between `render` and `redirect_to`
619
-
620
- Sometimes inexperienced developers think of `redirect_to` as a sort of `goto` command, moving execution from one place to another in your Rails code. This is _not_ correct. Your code stops running and waits for a new request for the browser. It just happens that you've told the browser what request it should make next, by sending back an HTTP 302 status code.
621
-
622
- Consider these actions to see the difference:
623
-
624
- ```ruby
625
- def index
626
- @books = Book.all
627
- end
628
-
629
- def show
630
- @book = Book.find_by(id: params[:id])
631
- if @book.nil?
632
- render action: "index"
633
- end
634
- end
635
- ```
636
-
637
- With the code in this form, there will likely be a problem if the `@book` variable is `nil`. Remember, a `render :action` doesn't run any code in the target action, so nothing will set up the `@books` variable that the `index` view will probably require. One way to fix this is to redirect instead of rendering:
638
-
639
- ```ruby
640
- def index
641
- @books = Book.all
642
- end
643
-
644
- def show
645
- @book = Book.find_by(id: params[:id])
646
- if @book.nil?
647
- redirect_to action: :index
648
- end
649
- end
650
- ```
651
-
652
- With this code, the browser will make a fresh request for the index page, the code in the `index` method will run, and all will be well.
653
-
654
- The only downside to this code is that it requires a round trip to the browser: the browser requested the show action with `/books/1` and the controller finds that there are no books, so the controller sends out a 302 redirect response to the browser telling it to go to `/books/`, the browser complies and sends a new request back to the controller asking now for the `index` action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen.
655
-
656
- While in a small application, this added latency might not be a problem, it is something to think about if response time is a concern. We can demonstrate one way to handle this with a contrived example:
657
-
658
- ```ruby
659
- def index
660
- @books = Book.all
661
- end
662
-
663
- def show
664
- @book = Book.find_by(id: params[:id])
665
- if @book.nil?
666
- @books = Book.all
667
- flash.now[:alert] = "Your book was not found"
668
- render "index"
669
- end
670
- end
671
- ```
672
-
673
- This would detect that there are no books with the specified ID, populate the `@books` instance variable with all the books in the model, and then directly render the `index.html.erb` template, returning it to the browser with a flash alert message to tell the user what happened.
674
-
675
- ### Using `head` To Build Header-Only Responses
676
-
677
- The `head` method can be used to send responses with only headers to the browser. It provides a more obvious alternative to calling `render :nothing`. The `head` method accepts a number or symbol (see [reference table](#the-status-option)) representing a HTTP status code. The options argument is interpreted as a hash of header names and values. For example, you can return only an error header:
678
-
679
- ```ruby
680
- head :bad_request
681
- ```
682
-
683
- This would produce the following header:
684
-
685
- ```
686
- HTTP/1.1 400 Bad Request
687
- Connection: close
688
- Date: Sun, 24 Jan 2010 12:15:53 GMT
689
- Transfer-Encoding: chunked
690
- Content-Type: text/html; charset=utf-8
691
- X-Runtime: 0.013483
692
- Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
693
- Cache-Control: no-cache
694
- ```
695
-
696
- Or you can use other HTTP headers to convey other information:
697
-
698
- ```ruby
699
- head :created, location: photo_path(@photo)
700
- ```
701
-
702
- Which would produce:
703
-
704
- ```
705
- HTTP/1.1 201 Created
706
- Connection: close
707
- Date: Sun, 24 Jan 2010 12:16:44 GMT
708
- Transfer-Encoding: chunked
709
- Location: /photos/1
710
- Content-Type: text/html; charset=utf-8
711
- X-Runtime: 0.083496
712
- Set-Cookie: _blog_session=...snip...; path=/; HttpOnly
713
- Cache-Control: no-cache
714
- ```
715
-
716
- Structuring Layouts
717
- -------------------
718
-
719
- When Rails renders a view as a response, it does so by combining the view with the current layout, using the rules for finding the current layout that were covered earlier in this guide. Within a layout, you have access to three tools for combining different bits of output to form the overall response:
720
-
721
- * Asset tags
722
- * `yield` and `content_for`
723
- * Partials
724
-
725
- ### Asset Tag Helpers
726
-
727
- Asset tag helpers provide methods for generating HTML that link views to feeds, JavaScript, stylesheets, images, videos and audios. There are six asset tag helpers available in Rails:
728
-
729
- * `auto_discovery_link_tag`
730
- * `javascript_include_tag`
731
- * `stylesheet_link_tag`
732
- * `image_tag`
733
- * `video_tag`
734
- * `audio_tag`
735
-
736
- You can use these tags in layouts or other views, although the `auto_discovery_link_tag`, `javascript_include_tag`, and `stylesheet_link_tag`, are most commonly used in the `<head>` section of a layout.
737
-
738
- WARNING: The asset tag helpers do _not_ verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link.
739
-
740
- #### Linking to Feeds with the `auto_discovery_link_tag`
741
-
742
- The `auto_discovery_link_tag` helper builds HTML that most browsers and feed readers can use to detect the presence of RSS or Atom feeds. It takes the type of the link (`:rss` or `:atom`), a hash of options that are passed through to url_for, and a hash of options for the tag:
743
-
744
- ```erb
745
- <%= auto_discovery_link_tag(:rss, {action: "feed"},
746
- {title: "RSS Feed"}) %>
747
- ```
748
-
749
- There are three tag options available for the `auto_discovery_link_tag`:
750
-
751
- * `:rel` specifies the `rel` value in the link. The default value is "alternate".
752
- * `:type` specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically.
753
- * `:title` specifies the title of the link. The default value is the uppercase `:type` value, for example, "ATOM" or "RSS".
754
-
755
- #### Linking to JavaScript Files with the `javascript_include_tag`
756
-
757
- The `javascript_include_tag` helper returns an HTML `script` tag for each source provided.
758
-
759
- If you are using Rails with the [Asset Pipeline](asset_pipeline.html) enabled, this helper will generate a link to `/assets/javascripts/` rather than `public/javascripts` which was used in earlier versions of Rails. This link is then served by the asset pipeline.
760
-
761
- A JavaScript file within a Rails application or Rails engine goes in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`. These locations are explained in detail in the [Asset Organization section in the Asset Pipeline Guide](asset_pipeline.html#asset-organization)
762
-
763
- You can specify a full path relative to the document root, or a URL, if you prefer. For example, to link to a JavaScript file that is inside a directory called `javascripts` inside of one of `app/assets`, `lib/assets` or `vendor/assets`, you would do this:
764
-
765
- ```erb
766
- <%= javascript_include_tag "main" %>
767
- ```
768
-
769
- Rails will then output a `script` tag such as this:
770
-
771
- ```html
772
- <script src='/assets/main.js'></script>
773
- ```
774
-
775
- The request to this asset is then served by the Sprockets gem.
776
-
777
- To include multiple files such as `app/assets/javascripts/main.js` and `app/assets/javascripts/columns.js` at the same time:
778
-
779
- ```erb
780
- <%= javascript_include_tag "main", "columns" %>
781
- ```
782
-
783
- To include `app/assets/javascripts/main.js` and `app/assets/javascripts/photos/columns.js`:
784
-
785
- ```erb
786
- <%= javascript_include_tag "main", "/photos/columns" %>
787
- ```
788
-
789
- To include `http://example.com/main.js`:
790
-
791
- ```erb
792
- <%= javascript_include_tag "http://example.com/main.js" %>
793
- ```
794
-
795
- #### Linking to CSS Files with the `stylesheet_link_tag`
796
-
797
- The `stylesheet_link_tag` helper returns an HTML `<link>` tag for each source provided.
798
-
799
- If you are using Rails with the "Asset Pipeline" enabled, this helper will generate a link to `/assets/stylesheets/`. This link is then processed by the Sprockets gem. A stylesheet file can be stored in one of three locations: `app/assets`, `lib/assets` or `vendor/assets`.
800
-
801
- You can specify a full path relative to the document root, or a URL. For example, to link to a stylesheet file that is inside a directory called `stylesheets` inside of one of `app/assets`, `lib/assets` or `vendor/assets`, you would do this:
802
-
803
- ```erb
804
- <%= stylesheet_link_tag "main" %>
805
- ```
806
-
807
- To include `app/assets/stylesheets/main.css` and `app/assets/stylesheets/columns.css`:
808
-
809
- ```erb
810
- <%= stylesheet_link_tag "main", "columns" %>
811
- ```
812
-
813
- To include `app/assets/stylesheets/main.css` and `app/assets/stylesheets/photos/columns.css`:
814
-
815
- ```erb
816
- <%= stylesheet_link_tag "main", "photos/columns" %>
817
- ```
818
-
819
- To include `http://example.com/main.css`:
820
-
821
- ```erb
822
- <%= stylesheet_link_tag "http://example.com/main.css" %>
823
- ```
824
-
825
- By default, the `stylesheet_link_tag` creates links with `media="screen" rel="stylesheet"`. You can override any of these defaults by specifying an appropriate option (`:media`, `:rel`):
826
-
827
- ```erb
828
- <%= stylesheet_link_tag "main_print", media: "print" %>
829
- ```
830
-
831
- #### Linking to Images with the `image_tag`
832
-
833
- The `image_tag` helper builds an HTML `<img />` tag to the specified file. By default, files are loaded from `public/images`.
834
-
835
- WARNING: Note that you must specify the extension of the image.
836
-
837
- ```erb
838
- <%= image_tag "header.png" %>
839
- ```
840
-
841
- You can supply a path to the image if you like:
842
-
843
- ```erb
844
- <%= image_tag "icons/delete.gif" %>
845
- ```
846
-
847
- You can supply a hash of additional HTML options:
848
-
849
- ```erb
850
- <%= image_tag "icons/delete.gif", {height: 45} %>
851
- ```
852
-
853
- You can supply alternate text for the image which will be used if the user has images turned off in their browser. If you do not specify an alt text explicitly, it defaults to the file name of the file, capitalized and with no extension. For example, these two image tags would return the same code:
854
-
855
- ```erb
856
- <%= image_tag "home.gif" %>
857
- <%= image_tag "home.gif", alt: "Home" %>
858
- ```
859
-
860
- You can also specify a special size tag, in the format "{width}x{height}":
861
-
862
- ```erb
863
- <%= image_tag "home.gif", size: "50x20" %>
864
- ```
865
-
866
- In addition to the above special tags, you can supply a final hash of standard HTML options, such as `:class`, `:id` or `:name`:
867
-
868
- ```erb
869
- <%= image_tag "home.gif", alt: "Go Home",
870
- id: "HomeImage",
871
- class: "nav_bar" %>
872
- ```
873
-
874
- #### Linking to Videos with the `video_tag`
875
-
876
- The `video_tag` helper builds an HTML 5 `<video>` tag to the specified file. By default, files are loaded from `public/videos`.
877
-
878
- ```erb
879
- <%= video_tag "movie.ogg" %>
880
- ```
881
-
882
- Produces
883
-
884
- ```erb
885
- <video src="/videos/movie.ogg" />
886
- ```
887
-
888
- Like an `image_tag` you can supply a path, either absolute, or relative to the `public/videos` directory. Additionally you can specify the `size: "#{width}x#{height}"` option just like an `image_tag`. Video tags can also have any of the HTML options specified at the end (`id`, `class` et al).
889
-
890
- The video tag also supports all of the `<video>` HTML options through the HTML options hash, including:
891
-
892
- * `poster: "image_name.png"`, provides an image to put in place of the video before it starts playing.
893
- * `autoplay: true`, starts playing the video on page load.
894
- * `loop: true`, loops the video once it gets to the end.
895
- * `controls: true`, provides browser supplied controls for the user to interact with the video.
896
- * `autobuffer: true`, the video will pre load the file for the user on page load.
897
-
898
- You can also specify multiple videos to play by passing an array of videos to the `video_tag`:
899
-
900
- ```erb
901
- <%= video_tag ["trailer.ogg", "movie.ogg"] %>
902
- ```
903
-
904
- This will produce:
905
-
906
- ```erb
907
- <video><source src="/videos/trailer.ogg" /><source src="/videos/trailer.flv" /></video>
908
- ```
909
-
910
- #### Linking to Audio Files with the `audio_tag`
911
-
912
- The `audio_tag` helper builds an HTML 5 `<audio>` tag to the specified file. By default, files are loaded from `public/audios`.
913
-
914
- ```erb
915
- <%= audio_tag "music.mp3" %>
916
- ```
917
-
918
- You can supply a path to the audio file if you like:
919
-
920
- ```erb
921
- <%= audio_tag "music/first_song.mp3" %>
922
- ```
923
-
924
- You can also supply a hash of additional options, such as `:id`, `:class` etc.
925
-
926
- Like the `video_tag`, the `audio_tag` has special options:
927
-
928
- * `autoplay: true`, starts playing the audio on page load
929
- * `controls: true`, provides browser supplied controls for the user to interact with the audio.
930
- * `autobuffer: true`, the audio will pre load the file for the user on page load.
931
-
932
- ### Understanding `yield`
933
-
934
- Within the context of a layout, `yield` identifies a section where content from the view should be inserted. The simplest way to use this is to have a single `yield`, into which the entire contents of the view currently being rendered is inserted:
935
-
936
- ```html+erb
937
- <html>
938
- <head>
939
- </head>
940
- <body>
941
- <%= yield %>
942
- </body>
943
- </html>
944
- ```
945
-
946
- You can also create a layout with multiple yielding regions:
947
-
948
- ```html+erb
949
- <html>
950
- <head>
951
- <%= yield :head %>
952
- </head>
953
- <body>
954
- <%= yield %>
955
- </body>
956
- </html>
957
- ```
958
-
959
- The main body of the view will always render into the unnamed `yield`. To render content into a named `yield`, you use the `content_for` method.
960
-
961
- ### Using the `content_for` Method
962
-
963
- The `content_for` method allows you to insert content into a named `yield` block in your layout. For example, this view would work with the layout that you just saw:
964
-
965
- ```html+erb
966
- <% content_for :head do %>
967
- <title>A simple page</title>
968
- <% end %>
969
-
970
- <p>Hello, Rails!</p>
971
- ```
972
-
973
- The result of rendering this page into the supplied layout would be this HTML:
974
-
975
- ```html+erb
976
- <html>
977
- <head>
978
- <title>A simple page</title>
979
- </head>
980
- <body>
981
- <p>Hello, Rails!</p>
982
- </body>
983
- </html>
984
- ```
985
-
986
- The `content_for` method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It's also useful for inserting tags that load page-specific JavaScript or css files into the header of an otherwise generic layout.
987
-
988
- ### Using Partials
989
-
990
- Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
991
-
992
- #### Naming Partials
993
-
994
- To render a partial as part of a view, you use the `render` method within the view:
995
-
996
- ```ruby
997
- <%= render "menu" %>
998
- ```
999
-
1000
- This will render a file named `_menu.html.erb` at that point within the view being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:
1001
-
1002
- ```ruby
1003
- <%= render "shared/menu" %>
1004
- ```
1005
-
1006
- That code will pull in the partial from `app/views/shared/_menu.html.erb`.
1007
-
1008
- #### Using Partials to Simplify Views
1009
-
1010
- One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what's going on more easily. For example, you might have a view that looked like this:
1011
-
1012
- ```erb
1013
- <%= render "shared/ad_banner" %>
1014
-
1015
- <h1>Products</h1>
1016
-
1017
- <p>Here are a few of our fine products:</p>
1018
- ...
1019
-
1020
- <%= render "shared/footer" %>
1021
- ```
1022
-
1023
- Here, the `_ad_banner.html.erb` and `_footer.html.erb` partials could contain content that is shared among many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.
1024
-
1025
- TIP: For content that is shared among all pages in your application, you can use partials directly from layouts.
1026
-
1027
- #### Partial Layouts
1028
-
1029
- A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this:
1030
-
1031
- ```erb
1032
- <%= render partial: "link_area", layout: "graybar" %>
1033
- ```
1034
-
1035
- This would look for a partial named `_link_area.html.erb` and render it using the layout `_graybar.html.erb`. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master `layouts` folder).
1036
-
1037
- Also note that explicitly specifying `:partial` is required when passing additional options such as `:layout`.
1038
-
1039
- #### Passing Local Variables
1040
-
1041
- You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:
1042
-
1043
- * `new.html.erb`
1044
-
1045
- ```html+erb
1046
- <h1>New zone</h1>
1047
- <%= render partial: "form", locals: {zone: @zone} %>
1048
- ```
1049
-
1050
- * `edit.html.erb`
1051
-
1052
- ```html+erb
1053
- <h1>Editing zone</h1>
1054
- <%= render partial: "form", locals: {zone: @zone} %>
1055
- ```
1056
-
1057
- * `_form.html.erb`
1058
-
1059
- ```html+erb
1060
- <%= form_for(zone) do |f| %>
1061
- <p>
1062
- <b>Zone name</b><br>
1063
- <%= f.text_field :name %>
1064
- </p>
1065
- <p>
1066
- <%= f.submit %>
1067
- </p>
1068
- <% end %>
1069
- ```
1070
-
1071
- Although the same partial will be rendered into both views, Action View's submit helper will return "Create Zone" for the new action and "Update Zone" for the edit action.
1072
-
1073
- Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the `:object` option:
1074
-
1075
- ```erb
1076
- <%= render partial: "customer", object: @new_customer %>
1077
- ```
1078
-
1079
- Within the `customer` partial, the `customer` variable will refer to `@new_customer` from the parent view.
1080
-
1081
- If you have an instance of a model to render into a partial, you can use a shorthand syntax:
1082
-
1083
- ```erb
1084
- <%= render @customer %>
1085
- ```
1086
-
1087
- Assuming that the `@customer` instance variable contains an instance of the `Customer` model, this will use `_customer.html.erb` to render it and will pass the local variable `customer` into the partial which will refer to the `@customer` instance variable in the parent view.
1088
-
1089
- #### Rendering Collections
1090
-
1091
- Partials are very useful in rendering collections. When you pass a collection to a partial via the `:collection` option, the partial will be inserted once for each member in the collection:
1092
-
1093
- * `index.html.erb`
1094
-
1095
- ```html+erb
1096
- <h1>Products</h1>
1097
- <%= render partial: "product", collection: @products %>
1098
- ```
1099
-
1100
- * `_product.html.erb`
1101
-
1102
- ```html+erb
1103
- <p>Product Name: <%= product.name %></p>
1104
- ```
1105
-
1106
- When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is `_product`, and within the `_product` partial, you can refer to `product` to get the instance that is being rendered.
1107
-
1108
- There is also a shorthand for this. Assuming `@products` is a collection of `product` instances, you can simply write this in the `index.html.erb` to produce the same result:
1109
-
1110
- ```html+erb
1111
- <h1>Products</h1>
1112
- <%= render @products %>
1113
- ```
1114
-
1115
- Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection:
1116
-
1117
- * `index.html.erb`
1118
-
1119
- ```html+erb
1120
- <h1>Contacts</h1>
1121
- <%= render [customer1, employee1, customer2, employee2] %>
1122
- ```
1123
-
1124
- * `customers/_customer.html.erb`
1125
-
1126
- ```html+erb
1127
- <p>Customer: <%= customer.name %></p>
1128
- ```
1129
-
1130
- * `employees/_employee.html.erb`
1131
-
1132
- ```html+erb
1133
- <p>Employee: <%= employee.name %></p>
1134
- ```
1135
-
1136
- In this case, Rails will use the customer or employee partials as appropriate for each member of the collection.
1137
-
1138
- In the event that the collection is empty, `render` will return nil, so it should be fairly simple to provide alternative content.
1139
-
1140
- ```html+erb
1141
- <h1>Products</h1>
1142
- <%= render(@products) || "There are no products available." %>
1143
- ```
1144
-
1145
- #### Local Variables
1146
-
1147
- To use a custom local variable name within the partial, specify the `:as` option in the call to the partial:
1148
-
1149
- ```erb
1150
- <%= render partial: "product", collection: @products, as: :item %>
1151
- ```
1152
-
1153
- With this change, you can access an instance of the `@products` collection as the `item` local variable within the partial.
1154
-
1155
- You can also pass in arbitrary local variables to any partial you are rendering with the `locals: {}` option:
1156
-
1157
- ```erb
1158
- <%= render partial: "product", collection: @products,
1159
- as: :item, locals: {title: "Products Page"} %>
1160
- ```
1161
-
1162
- In this case, the partial will have access to a local variable `title` with the value "Products Page".
1163
-
1164
- TIP: Rails also makes a counter variable available within a partial called by the collection, named after the member of the collection followed by `_counter`. For example, if you're rendering `@products`, within the partial you can refer to `product_counter` to tell you how many times the partial has been rendered. This does not work in conjunction with the `as: :value` option.
1165
-
1166
- You can also specify a second partial to be rendered between instances of the main partial by using the `:spacer_template` option:
1167
-
1168
- #### Spacer Templates
1169
-
1170
- ```erb
1171
- <%= render partial: @products, spacer_template: "product_ruler" %>
1172
- ```
1173
-
1174
- Rails will render the `_product_ruler` partial (with no data passed in to it) between each pair of `_product` partials.
1175
-
1176
- #### Collection Partial Layouts
1177
-
1178
- When rendering collections it is also possible to use the `:layout` option:
1179
-
1180
- ```erb
1181
- <%= render partial: "product", collection: @products, layout: "special_layout" %>
1182
- ```
1183
-
1184
- The layout will be rendered together with the partial for each item in the collection. The current object and object_counter variables will be available in the layout as well, the same way they do within the partial.
1185
-
1186
- ### Using Nested Layouts
1187
-
1188
- You may find that your application requires a layout that differs slightly from your regular application layout to support one particular controller. Rather than repeating the main layout and editing it, you can accomplish this by using nested layouts (sometimes called sub-templates). Here's an example:
1189
-
1190
- Suppose you have the following `ApplicationController` layout:
1191
-
1192
- * `app/views/layouts/application.html.erb`
1193
-
1194
- ```html+erb
1195
- <html>
1196
- <head>
1197
- <title><%= @page_title or "Page Title" %></title>
1198
- <%= stylesheet_link_tag "layout" %>
1199
- <style><%= yield :stylesheets %></style>
1200
- </head>
1201
- <body>
1202
- <div id="top_menu">Top menu items here</div>
1203
- <div id="menu">Menu items here</div>
1204
- <div id="content"><%= content_for?(:content) ? yield(:content) : yield %></div>
1205
- </body>
1206
- </html>
1207
- ```
1208
-
1209
- On pages generated by `NewsController`, you want to hide the top menu and add a right menu:
1210
-
1211
- * `app/views/layouts/news.html.erb`
1212
-
1213
- ```html+erb
1214
- <% content_for :stylesheets do %>
1215
- #top_menu {display: none}
1216
- #right_menu {float: right; background-color: yellow; color: black}
1217
- <% end %>
1218
- <% content_for :content do %>
1219
- <div id="right_menu">Right menu items here</div>
1220
- <%= content_for?(:news_content) ? yield(:news_content) : yield %>
1221
- <% end %>
1222
- <%= render template: "layouts/application" %>
1223
- ```
1224
-
1225
- That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div.
1226
-
1227
- There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the `ActionView::render` method via `render template: 'layouts/news'` to base a new layout on the News layout. If you are sure you will not subtemplate the `News` layout, you can replace the `content_for?(:news_content) ? yield(:news_content) : yield` with simply `yield`.