rails 3.2.22.2 → 4.2.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (216) hide show
  1. checksums.yaml +7 -0
  2. data/README.md +85 -0
  3. data/guides/CHANGELOG.md +31 -0
  4. data/guides/Rakefile +79 -0
  5. data/guides/assets/images/akshaysurve.jpg +0 -0
  6. data/guides/assets/images/belongs_to.png +0 -0
  7. data/guides/assets/images/book_icon.gif +0 -0
  8. data/guides/assets/images/bullet.gif +0 -0
  9. data/guides/assets/images/chapters_icon.gif +0 -0
  10. data/guides/assets/images/check_bullet.gif +0 -0
  11. data/guides/assets/images/credits_pic_blank.gif +0 -0
  12. data/guides/assets/images/csrf.png +0 -0
  13. data/guides/assets/images/edge_badge.png +0 -0
  14. data/guides/assets/images/favicon.ico +0 -0
  15. data/guides/assets/images/feature_tile.gif +0 -0
  16. data/guides/assets/images/footer_tile.gif +0 -0
  17. data/guides/assets/images/fxn.png +0 -0
  18. data/guides/assets/images/getting_started/article_with_comments.png +0 -0
  19. data/guides/assets/images/getting_started/challenge.png +0 -0
  20. data/guides/assets/images/getting_started/confirm_dialog.png +0 -0
  21. data/guides/assets/images/getting_started/forbidden_attributes_for_new_article.png +0 -0
  22. data/guides/assets/images/getting_started/form_with_errors.png +0 -0
  23. data/guides/assets/images/getting_started/index_action_with_edit_link.png +0 -0
  24. data/guides/assets/images/getting_started/new_article.png +0 -0
  25. data/guides/assets/images/getting_started/rails_welcome.png +0 -0
  26. data/guides/assets/images/getting_started/routing_error_no_controller.png +0 -0
  27. data/guides/assets/images/getting_started/routing_error_no_route_matches.png +0 -0
  28. data/guides/assets/images/getting_started/show_action_for_articles.png +0 -0
  29. data/guides/assets/images/getting_started/template_is_missing_articles_new.png +0 -0
  30. data/guides/assets/images/getting_started/unknown_action_create_for_articles.png +0 -0
  31. data/guides/assets/images/getting_started/unknown_action_new_for_articles.png +0 -0
  32. data/guides/assets/images/grey_bullet.gif +0 -0
  33. data/guides/assets/images/habtm.png +0 -0
  34. data/guides/assets/images/has_many.png +0 -0
  35. data/guides/assets/images/has_many_through.png +0 -0
  36. data/guides/assets/images/has_one.png +0 -0
  37. data/guides/assets/images/has_one_through.png +0 -0
  38. data/guides/assets/images/header_backdrop.png +0 -0
  39. data/guides/assets/images/header_tile.gif +0 -0
  40. data/guides/assets/images/i18n/demo_html_safe.png +0 -0
  41. data/guides/assets/images/i18n/demo_localized_pirate.png +0 -0
  42. data/guides/assets/images/i18n/demo_translated_en.png +0 -0
  43. data/guides/assets/images/i18n/demo_translated_pirate.png +0 -0
  44. data/guides/assets/images/i18n/demo_translation_missing.png +0 -0
  45. data/guides/assets/images/i18n/demo_untranslated.png +0 -0
  46. data/guides/assets/images/icons/README +5 -0
  47. data/guides/assets/images/icons/callouts/1.png +0 -0
  48. data/guides/assets/images/icons/callouts/10.png +0 -0
  49. data/guides/assets/images/icons/callouts/11.png +0 -0
  50. data/guides/assets/images/icons/callouts/12.png +0 -0
  51. data/guides/assets/images/icons/callouts/13.png +0 -0
  52. data/guides/assets/images/icons/callouts/14.png +0 -0
  53. data/guides/assets/images/icons/callouts/15.png +0 -0
  54. data/guides/assets/images/icons/callouts/2.png +0 -0
  55. data/guides/assets/images/icons/callouts/3.png +0 -0
  56. data/guides/assets/images/icons/callouts/4.png +0 -0
  57. data/guides/assets/images/icons/callouts/5.png +0 -0
  58. data/guides/assets/images/icons/callouts/6.png +0 -0
  59. data/guides/assets/images/icons/callouts/7.png +0 -0
  60. data/guides/assets/images/icons/callouts/8.png +0 -0
  61. data/guides/assets/images/icons/callouts/9.png +0 -0
  62. data/guides/assets/images/icons/caution.png +0 -0
  63. data/guides/assets/images/icons/example.png +0 -0
  64. data/guides/assets/images/icons/home.png +0 -0
  65. data/guides/assets/images/icons/important.png +0 -0
  66. data/guides/assets/images/icons/next.png +0 -0
  67. data/guides/assets/images/icons/note.png +0 -0
  68. data/guides/assets/images/icons/prev.png +0 -0
  69. data/guides/assets/images/icons/tip.png +0 -0
  70. data/guides/assets/images/icons/up.png +0 -0
  71. data/guides/assets/images/icons/warning.png +0 -0
  72. data/guides/assets/images/nav_arrow.gif +0 -0
  73. data/guides/assets/images/oscardelben.jpg +0 -0
  74. data/guides/assets/images/polymorphic.png +0 -0
  75. data/guides/assets/images/radar.png +0 -0
  76. data/guides/assets/images/rails4_features.png +0 -0
  77. data/guides/assets/images/rails_guides_kindle_cover.jpg +0 -0
  78. data/guides/assets/images/rails_guides_logo.gif +0 -0
  79. data/guides/assets/images/rails_logo_remix.gif +0 -0
  80. data/guides/assets/images/session_fixation.png +0 -0
  81. data/guides/assets/images/tab_grey.gif +0 -0
  82. data/guides/assets/images/tab_info.gif +0 -0
  83. data/guides/assets/images/tab_note.gif +0 -0
  84. data/guides/assets/images/tab_red.gif +0 -0
  85. data/guides/assets/images/tab_yellow.gif +0 -0
  86. data/guides/assets/images/tab_yellow.png +0 -0
  87. data/guides/assets/images/vijaydev.jpg +0 -0
  88. data/guides/assets/javascripts/guides.js +59 -0
  89. data/guides/assets/javascripts/jquery.min.js +4 -0
  90. data/guides/assets/javascripts/responsive-tables.js +43 -0
  91. data/guides/assets/javascripts/syntaxhighlighter/shBrushAS3.js +59 -0
  92. data/guides/assets/javascripts/syntaxhighlighter/shBrushAppleScript.js +75 -0
  93. data/guides/assets/javascripts/syntaxhighlighter/shBrushBash.js +59 -0
  94. data/guides/assets/javascripts/syntaxhighlighter/shBrushCSharp.js +65 -0
  95. data/guides/assets/javascripts/syntaxhighlighter/shBrushColdFusion.js +100 -0
  96. data/guides/assets/javascripts/syntaxhighlighter/shBrushCpp.js +97 -0
  97. data/guides/assets/javascripts/syntaxhighlighter/shBrushCss.js +91 -0
  98. data/guides/assets/javascripts/syntaxhighlighter/shBrushDelphi.js +55 -0
  99. data/guides/assets/javascripts/syntaxhighlighter/shBrushDiff.js +41 -0
  100. data/guides/assets/javascripts/syntaxhighlighter/shBrushErlang.js +52 -0
  101. data/guides/assets/javascripts/syntaxhighlighter/shBrushGroovy.js +67 -0
  102. data/guides/assets/javascripts/syntaxhighlighter/shBrushJScript.js +52 -0
  103. data/guides/assets/javascripts/syntaxhighlighter/shBrushJava.js +57 -0
  104. data/guides/assets/javascripts/syntaxhighlighter/shBrushJavaFX.js +58 -0
  105. data/guides/assets/javascripts/syntaxhighlighter/shBrushPerl.js +72 -0
  106. data/guides/assets/javascripts/syntaxhighlighter/shBrushPhp.js +88 -0
  107. data/guides/assets/javascripts/syntaxhighlighter/shBrushPlain.js +33 -0
  108. data/guides/assets/javascripts/syntaxhighlighter/shBrushPowerShell.js +74 -0
  109. data/guides/assets/javascripts/syntaxhighlighter/shBrushPython.js +64 -0
  110. data/guides/assets/javascripts/syntaxhighlighter/shBrushRuby.js +55 -0
  111. data/guides/assets/javascripts/syntaxhighlighter/shBrushSass.js +94 -0
  112. data/guides/assets/javascripts/syntaxhighlighter/shBrushScala.js +51 -0
  113. data/guides/assets/javascripts/syntaxhighlighter/shBrushSql.js +66 -0
  114. data/guides/assets/javascripts/syntaxhighlighter/shBrushVb.js +56 -0
  115. data/guides/assets/javascripts/syntaxhighlighter/shBrushXml.js +69 -0
  116. data/guides/assets/javascripts/syntaxhighlighter/shCore.js +17 -0
  117. data/guides/assets/stylesheets/fixes.css +16 -0
  118. data/guides/assets/stylesheets/kindle.css +11 -0
  119. data/guides/assets/stylesheets/main.css +713 -0
  120. data/guides/assets/stylesheets/print.css +52 -0
  121. data/guides/assets/stylesheets/reset.css +43 -0
  122. data/guides/assets/stylesheets/responsive-tables.css +50 -0
  123. data/guides/assets/stylesheets/style.css +13 -0
  124. data/guides/assets/stylesheets/syntaxhighlighter/shCore.css +226 -0
  125. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDefault.css +328 -0
  126. data/guides/assets/stylesheets/syntaxhighlighter/shCoreDjango.css +331 -0
  127. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEclipse.css +339 -0
  128. data/guides/assets/stylesheets/syntaxhighlighter/shCoreEmacs.css +324 -0
  129. data/guides/assets/stylesheets/syntaxhighlighter/shCoreFadeToGrey.css +328 -0
  130. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMDUltra.css +324 -0
  131. data/guides/assets/stylesheets/syntaxhighlighter/shCoreMidnight.css +324 -0
  132. data/guides/assets/stylesheets/syntaxhighlighter/shCoreRDark.css +324 -0
  133. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDefault.css +117 -0
  134. data/guides/assets/stylesheets/syntaxhighlighter/shThemeDjango.css +120 -0
  135. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEclipse.css +128 -0
  136. data/guides/assets/stylesheets/syntaxhighlighter/shThemeEmacs.css +113 -0
  137. data/guides/assets/stylesheets/syntaxhighlighter/shThemeFadeToGrey.css +117 -0
  138. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMDUltra.css +113 -0
  139. data/guides/assets/stylesheets/syntaxhighlighter/shThemeMidnight.css +113 -0
  140. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRDark.css +113 -0
  141. data/guides/assets/stylesheets/syntaxhighlighter/shThemeRailsGuides.css +116 -0
  142. data/guides/bug_report_templates/action_controller_gem.rb +47 -0
  143. data/guides/bug_report_templates/action_controller_master.rb +54 -0
  144. data/guides/bug_report_templates/active_record_gem.rb +40 -0
  145. data/guides/bug_report_templates/active_record_master.rb +49 -0
  146. data/guides/rails_guides/generator.rb +248 -0
  147. data/guides/rails_guides/helpers.rb +53 -0
  148. data/guides/rails_guides/indexer.rb +68 -0
  149. data/guides/rails_guides/kindle.rb +119 -0
  150. data/guides/rails_guides/levenshtein.rb +39 -0
  151. data/guides/rails_guides/markdown/renderer.rb +82 -0
  152. data/guides/rails_guides/markdown.rb +167 -0
  153. data/guides/rails_guides.rb +63 -0
  154. data/guides/source/2_2_release_notes.md +435 -0
  155. data/guides/source/2_3_release_notes.md +621 -0
  156. data/guides/source/3_0_release_notes.md +611 -0
  157. data/guides/source/3_1_release_notes.md +559 -0
  158. data/guides/source/3_2_release_notes.md +568 -0
  159. data/guides/source/4_0_release_notes.md +279 -0
  160. data/guides/source/4_1_release_notes.md +730 -0
  161. data/guides/source/4_2_release_notes.md +850 -0
  162. data/guides/source/_license.html.erb +2 -0
  163. data/guides/source/_welcome.html.erb +19 -0
  164. data/guides/source/action_controller_overview.md +1249 -0
  165. data/guides/source/action_mailer_basics.md +752 -0
  166. data/guides/source/action_view_overview.md +1620 -0
  167. data/guides/source/active_job_basics.md +318 -0
  168. data/guides/source/active_model_basics.md +554 -0
  169. data/guides/source/active_record_basics.md +374 -0
  170. data/guides/source/active_record_callbacks.md +413 -0
  171. data/guides/source/active_record_migrations.md +1018 -0
  172. data/guides/source/active_record_postgresql.md +433 -0
  173. data/guides/source/active_record_querying.md +1783 -0
  174. data/guides/source/active_record_validations.md +1178 -0
  175. data/guides/source/active_support_core_extensions.md +3904 -0
  176. data/guides/source/active_support_instrumentation.md +499 -0
  177. data/guides/source/api_documentation_guidelines.md +361 -0
  178. data/guides/source/asset_pipeline.md +1360 -0
  179. data/guides/source/association_basics.md +2236 -0
  180. data/guides/source/caching_with_rails.md +379 -0
  181. data/guides/source/command_line.md +625 -0
  182. data/guides/source/configuring.md +1045 -0
  183. data/guides/source/constant_autoloading_and_reloading.md +1297 -0
  184. data/guides/source/contributing_to_ruby_on_rails.md +624 -0
  185. data/guides/source/credits.html.erb +80 -0
  186. data/guides/source/debugging_rails_applications.md +861 -0
  187. data/guides/source/development_dependencies_install.md +289 -0
  188. data/guides/source/documents.yaml +205 -0
  189. data/guides/source/engines.md +1412 -0
  190. data/guides/source/form_helpers.md +1024 -0
  191. data/guides/source/generators.md +676 -0
  192. data/guides/source/getting_started.md +2085 -0
  193. data/guides/source/i18n.md +1086 -0
  194. data/guides/source/index.html.erb +28 -0
  195. data/guides/source/initialization.md +704 -0
  196. data/guides/source/kindle/copyright.html.erb +1 -0
  197. data/guides/source/kindle/layout.html.erb +27 -0
  198. data/guides/source/kindle/rails_guides.opf.erb +52 -0
  199. data/guides/source/kindle/toc.html.erb +24 -0
  200. data/guides/source/kindle/toc.ncx.erb +64 -0
  201. data/guides/source/kindle/welcome.html.erb +5 -0
  202. data/guides/source/layout.html.erb +143 -0
  203. data/guides/source/layouts_and_rendering.md +1227 -0
  204. data/guides/source/maintenance_policy.md +78 -0
  205. data/guides/source/nested_model_forms.md +228 -0
  206. data/guides/source/plugins.md +444 -0
  207. data/guides/source/rails_application_templates.md +266 -0
  208. data/guides/source/rails_on_rack.md +336 -0
  209. data/guides/source/routing.md +1141 -0
  210. data/guides/source/ruby_on_rails_guides_guidelines.md +127 -0
  211. data/guides/source/security.md +1024 -0
  212. data/guides/source/testing.md +1123 -0
  213. data/guides/source/upgrading_ruby_on_rails.md +1154 -0
  214. data/guides/source/working_with_javascript_in_rails.md +407 -0
  215. data/guides/w3c_validator.rb +97 -0
  216. metadata +290 -44
@@ -0,0 +1,1620 @@
1
+ Action View Overview
2
+ ====================
3
+
4
+ After reading this guide, you will know:
5
+
6
+ * What Action View is and how to use it with Rails.
7
+ * How best to use templates, partials, and layouts.
8
+ * What helpers are provided by Action View and how to make your own.
9
+ * How to use localized views.
10
+
11
+ --------------------------------------------------------------------------------
12
+
13
+ What is Action View?
14
+ --------------------
15
+
16
+ Action View and Action Controller are the two major components of Action Pack. In Rails, web requests are handled by Action Pack, which splits the work into a controller part (performing the logic) and a view part (rendering a template). Typically, Action Controller will be concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response.
17
+
18
+ Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It's also easy to add new helpers to your application as it evolves.
19
+
20
+ NOTE: Some features of Action View are tied to Active Record, but that doesn't mean Action View depends on Active Record. Action View is an independent package that can be used with any sort of Ruby libraries.
21
+
22
+ Using Action View with Rails
23
+ ----------------------------
24
+
25
+ For each controller there is an associated directory in the `app/views` directory which holds the template files that make up the views associated with that controller. These files are used to display the view that results from each controller action.
26
+
27
+ Let's take a look at what Rails does by default when creating a new resource using the scaffold generator:
28
+
29
+ ```bash
30
+ $ bin/rails generate scaffold article
31
+ [...]
32
+ invoke scaffold_controller
33
+ create app/controllers/articles_controller.rb
34
+ invoke erb
35
+ create app/views/articles
36
+ create app/views/articles/index.html.erb
37
+ create app/views/articles/edit.html.erb
38
+ create app/views/articles/show.html.erb
39
+ create app/views/articles/new.html.erb
40
+ create app/views/articles/_form.html.erb
41
+ [...]
42
+ ```
43
+
44
+ There is a naming convention for views in Rails. Typically, the views share their name with the associated controller action, as you can see above.
45
+ For example, the index controller action of the `articles_controller.rb` will use the `index.html.erb` view file in the `app/views/articles` directory.
46
+ The complete HTML returned to the client is composed of a combination of this ERB file, a layout template that wraps it, and all the partials that the view may reference. Within this guide you will find more detailed documentation about each of these three components.
47
+
48
+
49
+ Templates, Partials and Layouts
50
+ -------------------------------
51
+
52
+ As mentioned, the final HTML output is a composition of three Rails elements: `Templates`, `Partials` and `Layouts`.
53
+ Below is a brief overview of each of them.
54
+
55
+ ### Templates
56
+
57
+ Action View templates can be written in several ways. If the template file has a `.erb` extension then it uses a mixture of ERB (Embedded Ruby) and HTML. If the template file has a `.builder` extension then the `Builder::XmlMarkup` library is used.
58
+
59
+ Rails supports multiple template systems and uses a file extension to distinguish amongst them. For example, an HTML file using the ERB template system will have `.html.erb` as a file extension.
60
+
61
+ #### ERB
62
+
63
+ Within an ERB template, Ruby code can be included using both `<% %>` and `<%= %>` tags. The `<% %>` tags are used to execute Ruby code that does not return anything, such as conditions, loops or blocks, and the `<%= %>` tags are used when you want output.
64
+
65
+ Consider the following loop for names:
66
+
67
+ ```html+erb
68
+ <h1>Names of all the people</h1>
69
+ <% @people.each do |person| %>
70
+ Name: <%= person.name %><br>
71
+ <% end %>
72
+ ```
73
+
74
+ The loop is set up using regular embedding tags (`<% %>`) and the name is inserted using the output embedding tags (`<%= %>`). Note that this is not just a usage suggestion: regular output functions such as `print` and `puts` won't be rendered to the view with ERB templates. So this would be wrong:
75
+
76
+ ```html+erb
77
+ <%# WRONG %>
78
+ Hi, Mr. <% puts "Frodo" %>
79
+ ```
80
+
81
+ To suppress leading and trailing whitespaces, you can use `<%-` `-%>` interchangeably with `<%` and `%>`.
82
+
83
+ #### Builder
84
+
85
+ Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object named `xml` is automatically made available to templates with a `.builder` extension.
86
+
87
+ Here are some basic examples:
88
+
89
+ ```ruby
90
+ xml.em("emphasized")
91
+ xml.em { xml.b("emph & bold") }
92
+ xml.a("A Link", "href" => "http://rubyonrails.org")
93
+ xml.target("name" => "compile", "option" => "fast")
94
+ ```
95
+
96
+ which would produce:
97
+
98
+ ```html
99
+ <em>emphasized</em>
100
+ <em><b>emph &amp; bold</b></em>
101
+ <a href="http://rubyonrails.org">A link</a>
102
+ <target option="fast" name="compile" />
103
+ ```
104
+
105
+ Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
106
+
107
+ ```ruby
108
+ xml.div {
109
+ xml.h1(@person.name)
110
+ xml.p(@person.bio)
111
+ }
112
+ ```
113
+
114
+ would produce something like:
115
+
116
+ ```html
117
+ <div>
118
+ <h1>David Heinemeier Hansson</h1>
119
+ <p>A product of Danish Design during the Winter of '79...</p>
120
+ </div>
121
+ ```
122
+
123
+ Below is a full-length RSS example actually used on Basecamp:
124
+
125
+ ```ruby
126
+ xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do
127
+ xml.channel do
128
+ xml.title(@feed_title)
129
+ xml.link(@url)
130
+ xml.description "Basecamp: Recent items"
131
+ xml.language "en-us"
132
+ xml.ttl "40"
133
+
134
+ for item in @recent_items
135
+ xml.item do
136
+ xml.title(item_title(item))
137
+ xml.description(item_description(item)) if item_description(item)
138
+ xml.pubDate(item_pubDate(item))
139
+ xml.guid(@person.firm.account.url + @recent_items.url(item))
140
+ xml.link(@person.firm.account.url + @recent_items.url(item))
141
+ xml.tag!("dc:creator", item.author_name) if item_has_creator?(item)
142
+ end
143
+ end
144
+ end
145
+ end
146
+ ```
147
+
148
+ #### Template Caching
149
+
150
+ By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will check the file's modification time and recompile it in development mode.
151
+
152
+ ### Partials
153
+
154
+ Partial templates - usually just called "partials" - are another device for breaking the rendering process into more manageable chunks. With partials, you can extract pieces of code from your templates to separate files and also reuse them throughout your templates.
155
+
156
+ #### Naming Partials
157
+
158
+ To render a partial as part of a view, you use the `render` method within the view:
159
+
160
+ ```erb
161
+ <%= render "menu" %>
162
+ ```
163
+
164
+ This will render a file named `_menu.html.erb` at that point within the view that is 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:
165
+
166
+ ```erb
167
+ <%= render "shared/menu" %>
168
+ ```
169
+
170
+ That code will pull in the partial from `app/views/shared/_menu.html.erb`.
171
+
172
+ #### Using Partials to simplify Views
173
+
174
+ One way to use partials is to treat them as the equivalent of subroutines; 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 looks like this:
175
+
176
+ ```html+erb
177
+ <%= render "shared/ad_banner" %>
178
+
179
+ <h1>Products</h1>
180
+
181
+ <p>Here are a few of our fine products:</p>
182
+ <% @products.each do |product| %>
183
+ <%= render partial: "product", locals: {product: product} %>
184
+ <% end %>
185
+
186
+ <%= render "shared/footer" %>
187
+ ```
188
+
189
+ 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.
190
+
191
+ #### The `as` and `object` options
192
+
193
+ By default `ActionView::Partials::PartialRenderer` has its object in a local variable with the same name as the template. So, given:
194
+
195
+ ```erb
196
+ <%= render partial: "product" %>
197
+ ```
198
+
199
+ within product we'll get `@product` in the local variable `product`, as if we had written:
200
+
201
+ ```erb
202
+ <%= render partial: "product", locals: {product: @product} %>
203
+ ```
204
+
205
+ With the `as` option we can specify a different name for the local variable. For example, if we wanted it to be `item` instead of `product` we would do:
206
+
207
+ ```erb
208
+ <%= render partial: "product", as: "item" %>
209
+ ```
210
+
211
+ The `object` option can be used to directly specify which object is rendered into the partial; useful when the template's object is elsewhere (eg. in a different instance variable or in a local variable).
212
+
213
+ For example, instead of:
214
+
215
+ ```erb
216
+ <%= render partial: "product", locals: {product: @item} %>
217
+ ```
218
+
219
+ we would do:
220
+
221
+ ```erb
222
+ <%= render partial: "product", object: @item %>
223
+ ```
224
+
225
+ The `object` and `as` options can also be used together:
226
+
227
+ ```erb
228
+ <%= render partial: "product", object: @item, as: "item" %>
229
+ ```
230
+
231
+ #### Rendering Collections
232
+
233
+ It is very common that a template will need to iterate over a collection and render a sub-template for each of the elements. This pattern has been implemented as a single method that accepts an array and renders a partial for each one of the elements in the array.
234
+
235
+ So this example for rendering all the products:
236
+
237
+ ```erb
238
+ <% @products.each do |product| %>
239
+ <%= render partial: "product", locals: { product: product } %>
240
+ <% end %>
241
+ ```
242
+
243
+ can be rewritten in a single line:
244
+
245
+ ```erb
246
+ <%= render partial: "product", collection: @products %>
247
+ ```
248
+
249
+ When a partial is called with a collection, 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 it you can refer to `product` to get the collection member that is being rendered.
250
+
251
+ You can use a shorthand syntax for rendering collections. Assuming `@products` is a collection of `Product` instances, you can simply write the following to produce the same result:
252
+
253
+ ```erb
254
+ <%= render @products %>
255
+ ```
256
+
257
+ Rails determines the name of the partial to use by looking at the model name in the collection, `Product` in this case. In fact, you can even render a collection made up of instances of different models using this shorthand, and Rails will choose the proper partial for each member of the collection.
258
+
259
+ #### Spacer Templates
260
+
261
+ You can also specify a second partial to be rendered between instances of the main partial by using the `:spacer_template` option:
262
+
263
+ ```erb
264
+ <%= render partial: @products, spacer_template: "product_ruler" %>
265
+ ```
266
+
267
+ Rails will render the `_product_ruler` partial (with no data passed to it) between each pair of `_product` partials.
268
+
269
+ ### Layouts
270
+
271
+ Layouts can be used to render a common view template around the results of Rails controller actions. Typically, a Rails application will have a couple of layouts that pages will be rendered within. For example, a site might have one layout for a logged in user and another for the marketing or sales side of the site. The logged in user layout might include top-level navigation that should be present across many controller actions. The sales layout for a SaaS app might include top-level navigation for things like "Pricing" and "Contact Us" pages. You would expect each layout to have a different look and feel. You can read about layouts in more detail in the [Layouts and Rendering in Rails](layouts_and_rendering.html) guide.
272
+
273
+ Partial Layouts
274
+ ---------------
275
+
276
+ Partials can have their own layouts applied to them. These layouts are different from those applied to a controller action, but they work in a similar fashion.
277
+
278
+ Let's say we're displaying an article on a page which should be wrapped in a `div` for display purposes. Firstly, we'll create a new `Article`:
279
+
280
+ ```ruby
281
+ Article.create(body: 'Partial Layouts are cool!')
282
+ ```
283
+
284
+ In the `show` template, we'll render the `_article` partial wrapped in the `box` layout:
285
+
286
+ **articles/show.html.erb**
287
+
288
+ ```erb
289
+ <%= render partial: 'article', layout: 'box', locals: {article: @article} %>
290
+ ```
291
+
292
+ The `box` layout simply wraps the `_article` partial in a `div`:
293
+
294
+ **articles/_box.html.erb**
295
+
296
+ ```html+erb
297
+ <div class='box'>
298
+ <%= yield %>
299
+ </div>
300
+ ```
301
+
302
+ The `_article` partial wraps the article's `body` in a `div` with the `id` of the article using the `div_for` helper:
303
+
304
+ **articles/_article.html.erb**
305
+
306
+ ```html+erb
307
+ <%= div_for(article) do %>
308
+ <p><%= article.body %></p>
309
+ <% end %>
310
+ ```
311
+
312
+ this would output the following:
313
+
314
+ ```html
315
+ <div class='box'>
316
+ <div id='article_1'>
317
+ <p>Partial Layouts are cool!</p>
318
+ </div>
319
+ </div>
320
+ ```
321
+
322
+ Note that the partial layout has access to the local `article` variable that was passed into the `render` call. However, unlike application-wide layouts, partial layouts still have the underscore prefix.
323
+
324
+ You can also render a block of code within a partial layout instead of calling `yield`. For example, if we didn't have the `_article` partial, we could do this instead:
325
+
326
+ **articles/show.html.erb**
327
+
328
+ ```html+erb
329
+ <% render(layout: 'box', locals: {article: @article}) do %>
330
+ <%= div_for(article) do %>
331
+ <p><%= article.body %></p>
332
+ <% end %>
333
+ <% end %>
334
+ ```
335
+
336
+ Supposing we use the same `_box` partial from above, this would produce the same output as the previous example.
337
+
338
+ View Paths
339
+ ----------
340
+
341
+ TODO...
342
+
343
+ Overview of helpers provided by Action View
344
+ -------------------------------------------
345
+
346
+ WIP: Not all the helpers are listed here. For a full list see the [API documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html)
347
+
348
+ The following is only a brief overview summary of the helpers available in Action View. It's recommended that you review the [API Documentation](http://api.rubyonrails.org/classes/ActionView/Helpers.html), which covers all of the helpers in more detail, but this should serve as a good starting point.
349
+
350
+ ### RecordTagHelper
351
+
352
+ This module provides methods for generating container tags, such as `div`, for your record. This is the recommended way of creating a container for render your Active Record object, as it adds an appropriate class and id attributes to that container. You can then refer to those containers easily by following the convention, instead of having to think about which class or id attribute you should use.
353
+
354
+ #### content_tag_for
355
+
356
+ Renders a container tag that relates to your Active Record Object.
357
+
358
+ For example, given `@article` is the object of `Article` class, you can do:
359
+
360
+ ```html+erb
361
+ <%= content_tag_for(:tr, @article) do %>
362
+ <td><%= @article.title %></td>
363
+ <% end %>
364
+ ```
365
+
366
+ This will generate this HTML output:
367
+
368
+ ```html
369
+ <tr id="article_1234" class="article">
370
+ <td>Hello World!</td>
371
+ </tr>
372
+ ```
373
+
374
+ You can also supply HTML attributes as an additional option hash. For example:
375
+
376
+ ```html+erb
377
+ <%= content_tag_for(:tr, @article, class: "frontpage") do %>
378
+ <td><%= @article.title %></td>
379
+ <% end %>
380
+ ```
381
+
382
+ Will generate this HTML output:
383
+
384
+ ```html
385
+ <tr id="article_1234" class="article frontpage">
386
+ <td>Hello World!</td>
387
+ </tr>
388
+ ```
389
+
390
+ You can pass a collection of Active Record objects. This method will loop through your objects and create a container for each of them. For example, given `@articles` is an array of two `Article` objects:
391
+
392
+ ```html+erb
393
+ <%= content_tag_for(:tr, @articles) do |article| %>
394
+ <td><%= article.title %></td>
395
+ <% end %>
396
+ ```
397
+
398
+ Will generate this HTML output:
399
+
400
+ ```html
401
+ <tr id="article_1234" class="article">
402
+ <td>Hello World!</td>
403
+ </tr>
404
+ <tr id="article_1235" class="article">
405
+ <td>Ruby on Rails Rocks!</td>
406
+ </tr>
407
+ ```
408
+
409
+ #### div_for
410
+
411
+ This is actually a convenient method which calls `content_tag_for` internally with `:div` as the tag name. You can pass either an Active Record object or a collection of objects. For example:
412
+
413
+ ```html+erb
414
+ <%= div_for(@article, class: "frontpage") do %>
415
+ <td><%= @article.title %></td>
416
+ <% end %>
417
+ ```
418
+
419
+ Will generate this HTML output:
420
+
421
+ ```html
422
+ <div id="article_1234" class="article frontpage">
423
+ <td>Hello World!</td>
424
+ </div>
425
+ ```
426
+
427
+ ### AssetTagHelper
428
+
429
+ This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds.
430
+
431
+ By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting `config.action_controller.asset_host` in the application configuration, typically in `config/environments/production.rb`. For example, let's say your asset host is `assets.example.com`:
432
+
433
+ ```ruby
434
+ config.action_controller.asset_host = "assets.example.com"
435
+ image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
436
+ ```
437
+
438
+ #### register_javascript_expansion
439
+
440
+ Register one or more JavaScript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register JavaScript files that the plugin installed in `vendor/assets/javascripts`.
441
+
442
+ ```ruby
443
+ ActionView::Helpers::AssetTagHelper.register_javascript_expansion monkey: ["head", "body", "tail"]
444
+
445
+ javascript_include_tag :monkey # =>
446
+ <script src="/assets/head.js"></script>
447
+ <script src="/assets/body.js"></script>
448
+ <script src="/assets/tail.js"></script>
449
+ ```
450
+
451
+ #### register_stylesheet_expansion
452
+
453
+ Register one or more stylesheet files to be included when symbol is passed to `stylesheet_link_tag`. This method is typically intended to be called from plugin initialization to register stylesheet files that the plugin installed in `vendor/assets/stylesheets`.
454
+
455
+ ```ruby
456
+ ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion monkey: ["head", "body", "tail"]
457
+
458
+ stylesheet_link_tag :monkey # =>
459
+ <link href="/assets/head.css" media="screen" rel="stylesheet" />
460
+ <link href="/assets/body.css" media="screen" rel="stylesheet" />
461
+ <link href="/assets/tail.css" media="screen" rel="stylesheet" />
462
+ ```
463
+
464
+ #### auto_discovery_link_tag
465
+
466
+ Returns a link tag that browsers and feed readers can use to auto-detect an RSS or Atom feed.
467
+
468
+ ```ruby
469
+ auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {title: "RSS Feed"}) # =>
470
+ <link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed" />
471
+ ```
472
+
473
+ #### image_path
474
+
475
+ Computes the path to an image asset in the `app/assets/images` directory. Full paths from the document root will be passed through. Used internally by `image_tag` to build the image path.
476
+
477
+ ```ruby
478
+ image_path("edit.png") # => /assets/edit.png
479
+ ```
480
+
481
+ Fingerprint will be added to the filename if config.assets.digest is set to true.
482
+
483
+ ```ruby
484
+ image_path("edit.png") # => /assets/edit-2d1a2db63fc738690021fedb5a65b68e.png
485
+ ```
486
+
487
+ #### image_url
488
+
489
+ Computes the url to an image asset in the `app/assets/images` directory. This will call `image_path` internally and merge with your current host or your asset host.
490
+
491
+ ```ruby
492
+ image_url("edit.png") # => http://www.example.com/assets/edit.png
493
+ ```
494
+
495
+ #### image_tag
496
+
497
+ Returns an HTML image tag for the source. The source can be a full path or a file that exists in your `app/assets/images` directory.
498
+
499
+ ```ruby
500
+ image_tag("icon.png") # => <img src="/assets/icon.png" alt="Icon" />
501
+ ```
502
+
503
+ #### javascript_include_tag
504
+
505
+ Returns an HTML script tag for each of the sources provided. You can pass in the filename (`.js` extension is optional) of JavaScript files that exist in your `app/assets/javascripts` directory for inclusion into the current page or you can pass the full path relative to your document root.
506
+
507
+ ```ruby
508
+ javascript_include_tag "common" # => <script src="/assets/common.js"></script>
509
+ ```
510
+
511
+ If the application does not use the asset pipeline, to include the jQuery JavaScript library in your application, pass `:defaults` as the source. When using `:defaults`, if an `application.js` file exists in your `app/assets/javascripts` directory, it will be included as well.
512
+
513
+ ```ruby
514
+ javascript_include_tag :defaults
515
+ ```
516
+
517
+ You can also include all JavaScript files in the `app/assets/javascripts` directory using `:all` as the source.
518
+
519
+ ```ruby
520
+ javascript_include_tag :all
521
+ ```
522
+
523
+ You can also cache multiple JavaScript files into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if `ActionController::Base.perform_caching` is set to true (which is the case by default for the Rails production environment, but not for the development environment).
524
+
525
+ ```ruby
526
+ javascript_include_tag :all, cache: true # =>
527
+ <script src="/javascripts/all.js"></script>
528
+ ```
529
+
530
+ #### javascript_path
531
+
532
+ Computes the path to a JavaScript asset in the `app/assets/javascripts` directory. If the source filename has no extension, `.js` will be appended. Full paths from the document root will be passed through. Used internally by `javascript_include_tag` to build the script path.
533
+
534
+ ```ruby
535
+ javascript_path "common" # => /assets/common.js
536
+ ```
537
+
538
+ #### javascript_url
539
+
540
+ Computes the url to a JavaScript asset in the `app/assets/javascripts` directory. This will call `javascript_path` internally and merge with your current host or your asset host.
541
+
542
+ ```ruby
543
+ javascript_url "common" # => http://www.example.com/assets/common.js
544
+ ```
545
+
546
+ #### stylesheet_link_tag
547
+
548
+ Returns a stylesheet link tag for the sources specified as arguments. If you don't specify an extension, `.css` will be appended automatically.
549
+
550
+ ```ruby
551
+ stylesheet_link_tag "application" # => <link href="/assets/application.css" media="screen" rel="stylesheet" />
552
+ ```
553
+
554
+ You can also include all styles in the stylesheet directory using :all as the source:
555
+
556
+ ```ruby
557
+ stylesheet_link_tag :all
558
+ ```
559
+
560
+ You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching is set to true (which is the case by default for the Rails production environment, but not for the development environment).
561
+
562
+ ```ruby
563
+ stylesheet_link_tag :all, cache: true
564
+ # => <link href="/assets/all.css" media="screen" rel="stylesheet" />
565
+ ```
566
+
567
+ #### stylesheet_path
568
+
569
+ Computes the path to a stylesheet asset in the `app/assets/stylesheets` directory. If the source filename has no extension, .css will be appended. Full paths from the document root will be passed through. Used internally by stylesheet_link_tag to build the stylesheet path.
570
+
571
+ ```ruby
572
+ stylesheet_path "application" # => /assets/application.css
573
+ ```
574
+
575
+ #### stylesheet_url
576
+
577
+ Computes the url to a stylesheet asset in the `app/assets/stylesheets` directory. This will call `stylesheet_path` internally and merge with your current host or your asset host.
578
+
579
+ ```ruby
580
+ stylesheet_url "application" # => http://www.example.com/assets/application.css
581
+ ```
582
+
583
+ ### AtomFeedHelper
584
+
585
+ #### atom_feed
586
+
587
+ This helper makes building an Atom feed easy. Here's a full usage example:
588
+
589
+ **config/routes.rb**
590
+
591
+ ```ruby
592
+ resources :articles
593
+ ```
594
+
595
+ **app/controllers/articles_controller.rb**
596
+
597
+ ```ruby
598
+ def index
599
+ @articles = Article.all
600
+
601
+ respond_to do |format|
602
+ format.html
603
+ format.atom
604
+ end
605
+ end
606
+ ```
607
+
608
+ **app/views/articles/index.atom.builder**
609
+
610
+ ```ruby
611
+ atom_feed do |feed|
612
+ feed.title("Articles Index")
613
+ feed.updated((@articles.first.created_at))
614
+
615
+ @articles.each do |article|
616
+ feed.entry(article) do |entry|
617
+ entry.title(article.title)
618
+ entry.content(article.body, type: 'html')
619
+
620
+ entry.author do |author|
621
+ author.name(article.author_name)
622
+ end
623
+ end
624
+ end
625
+ end
626
+ ```
627
+
628
+ ### BenchmarkHelper
629
+
630
+ #### benchmark
631
+
632
+ Allows you to measure the execution time of a block in a template and records the result to the log. Wrap this block around expensive operations or possible bottlenecks to get a time reading for the operation.
633
+
634
+ ```html+erb
635
+ <% benchmark "Process data files" do %>
636
+ <%= expensive_files_operation %>
637
+ <% end %>
638
+ ```
639
+
640
+ This would add something like "Process data files (0.34523)" to the log, which you can then use to compare timings when optimizing your code.
641
+
642
+ ### CacheHelper
643
+
644
+ #### cache
645
+
646
+ A method for caching fragments of a view rather than an entire action or page. This technique is useful caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See `ActionController::Caching::Fragments` for more information.
647
+
648
+ ```erb
649
+ <% cache do %>
650
+ <%= render "shared/footer" %>
651
+ <% end %>
652
+ ```
653
+
654
+ ### CaptureHelper
655
+
656
+ #### capture
657
+
658
+ The `capture` method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout.
659
+
660
+ ```html+erb
661
+ <% @greeting = capture do %>
662
+ <p>Welcome! The date and time is <%= Time.now %></p>
663
+ <% end %>
664
+ ```
665
+
666
+ The captured variable can then be used anywhere else.
667
+
668
+ ```html+erb
669
+ <html>
670
+ <head>
671
+ <title>Welcome!</title>
672
+ </head>
673
+ <body>
674
+ <%= @greeting %>
675
+ </body>
676
+ </html>
677
+ ```
678
+
679
+ #### content_for
680
+
681
+ Calling `content_for` stores a block of markup in an identifier for later use. You can make subsequent calls to the stored content in other templates or the layout by passing the identifier as an argument to `yield`.
682
+
683
+ For example, let's say we have a standard application layout, but also a special page that requires certain JavaScript that the rest of the site doesn't need. We can use `content_for` to include this JavaScript on our special page without fattening up the rest of the site.
684
+
685
+ **app/views/layouts/application.html.erb**
686
+
687
+ ```html+erb
688
+ <html>
689
+ <head>
690
+ <title>Welcome!</title>
691
+ <%= yield :special_script %>
692
+ </head>
693
+ <body>
694
+ <p>Welcome! The date and time is <%= Time.now %></p>
695
+ </body>
696
+ </html>
697
+ ```
698
+
699
+ **app/views/articles/special.html.erb**
700
+
701
+ ```html+erb
702
+ <p>This is a special page.</p>
703
+
704
+ <% content_for :special_script do %>
705
+ <script>alert('Hello!')</script>
706
+ <% end %>
707
+ ```
708
+
709
+ ### DateHelper
710
+
711
+ #### date_select
712
+
713
+ Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute.
714
+
715
+ ```ruby
716
+ date_select("article", "published_on")
717
+ ```
718
+
719
+ #### datetime_select
720
+
721
+ Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based attribute.
722
+
723
+ ```ruby
724
+ datetime_select("article", "published_on")
725
+ ```
726
+
727
+ #### distance_of_time_in_words
728
+
729
+ Reports the approximate distance in time between two Time or Date objects or integers as seconds. Set `include_seconds` to true if you want more detailed approximations.
730
+
731
+ ```ruby
732
+ distance_of_time_in_words(Time.now, Time.now + 15.seconds) # => less than a minute
733
+ distance_of_time_in_words(Time.now, Time.now + 15.seconds, include_seconds: true) # => less than 20 seconds
734
+ ```
735
+
736
+ #### select_date
737
+
738
+ Returns a set of HTML select-tags (one for year, month, and day) pre-selected with the `date` provided.
739
+
740
+ ```ruby
741
+ # Generates a date select that defaults to the date provided (six days after today)
742
+ select_date(Time.today + 6.days)
743
+
744
+ # Generates a date select that defaults to today (no specified date)
745
+ select_date()
746
+ ```
747
+
748
+ #### select_datetime
749
+
750
+ Returns a set of HTML select-tags (one for year, month, day, hour, and minute) pre-selected with the `datetime` provided.
751
+
752
+ ```ruby
753
+ # Generates a datetime select that defaults to the datetime provided (four days after today)
754
+ select_datetime(Time.now + 4.days)
755
+
756
+ # Generates a datetime select that defaults to today (no specified datetime)
757
+ select_datetime()
758
+ ```
759
+
760
+ #### select_day
761
+
762
+ Returns a select tag with options for each of the days 1 through 31 with the current day selected.
763
+
764
+ ```ruby
765
+ # Generates a select field for days that defaults to the day for the date provided
766
+ select_day(Time.today + 2.days)
767
+
768
+ # Generates a select field for days that defaults to the number given
769
+ select_day(5)
770
+ ```
771
+
772
+ #### select_hour
773
+
774
+ Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
775
+
776
+ ```ruby
777
+ # Generates a select field for hours that defaults to the hours for the time provided
778
+ select_hour(Time.now + 6.hours)
779
+ ```
780
+
781
+ #### select_minute
782
+
783
+ Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
784
+
785
+ ```ruby
786
+ # Generates a select field for minutes that defaults to the minutes for the time provided.
787
+ select_minute(Time.now + 6.hours)
788
+ ```
789
+
790
+ #### select_month
791
+
792
+ Returns a select tag with options for each of the months January through December with the current month selected.
793
+
794
+ ```ruby
795
+ # Generates a select field for months that defaults to the current month
796
+ select_month(Date.today)
797
+ ```
798
+
799
+ #### select_second
800
+
801
+ Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
802
+
803
+ ```ruby
804
+ # Generates a select field for seconds that defaults to the seconds for the time provided
805
+ select_second(Time.now + 16.minutes)
806
+ ```
807
+
808
+ #### select_time
809
+
810
+ Returns a set of HTML select-tags (one for hour and minute).
811
+
812
+ ```ruby
813
+ # Generates a time select that defaults to the time provided
814
+ select_time(Time.now)
815
+ ```
816
+
817
+ #### select_year
818
+
819
+ Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius can be changed using the `:start_year` and `:end_year` keys in the `options`.
820
+
821
+ ```ruby
822
+ # Generates a select field for five years on either side of Date.today that defaults to the current year
823
+ select_year(Date.today)
824
+
825
+ # Generates a select field from 1900 to 2009 that defaults to the current year
826
+ select_year(Date.today, start_year: 1900, end_year: 2009)
827
+ ```
828
+
829
+ #### time_ago_in_words
830
+
831
+ Like `distance_of_time_in_words`, but where `to_time` is fixed to `Time.now`.
832
+
833
+ ```ruby
834
+ time_ago_in_words(3.minutes.from_now) # => 3 minutes
835
+ ```
836
+
837
+ #### time_select
838
+
839
+ Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a specified time-based attribute. The selects are prepared for multi-parameter assignment to an Active Record object.
840
+
841
+ ```ruby
842
+ # Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute
843
+ time_select("order", "submitted")
844
+ ```
845
+
846
+ ### DebugHelper
847
+
848
+ Returns a `pre` tag that has object dumped by YAML. This creates a very readable way to inspect an object.
849
+
850
+ ```ruby
851
+ my_hash = {'first' => 1, 'second' => 'two', 'third' => [1,2,3]}
852
+ debug(my_hash)
853
+ ```
854
+
855
+ ```html
856
+ <pre class='debug_dump'>---
857
+ first: 1
858
+ second: two
859
+ third:
860
+ - 1
861
+ - 2
862
+ - 3
863
+ </pre>
864
+ ```
865
+
866
+ ### FormHelper
867
+
868
+ Form helpers are designed to make working with models much easier compared to using just standard HTML elements by providing a set of methods for creating forms based on your models. This helper generates the HTML for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form is submitted (i.e., when the user hits the submit button or form.submit is called via JavaScript), the form inputs will be bundled into the params object and passed back to the controller.
869
+
870
+ There are two types of form helpers: those that specifically work with model attributes and those that don't. This helper deals with those that work with model attributes; to see an example of form helpers that don't work with model attributes, check the ActionView::Helpers::FormTagHelper documentation.
871
+
872
+ The core method of this helper, form_for, gives you the ability to create a form for a model instance; for example, let's say that you have a model Person and want to create a new instance of it:
873
+
874
+ ```html+erb
875
+ # Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
876
+ <%= form_for @person, url: {action: "create"} do |f| %>
877
+ <%= f.text_field :first_name %>
878
+ <%= f.text_field :last_name %>
879
+ <%= submit_tag 'Create' %>
880
+ <% end %>
881
+ ```
882
+
883
+ The HTML generated for this would be:
884
+
885
+ ```html
886
+ <form action="/people/create" method="post">
887
+ <input id="person_first_name" name="person[first_name]" type="text" />
888
+ <input id="person_last_name" name="person[last_name]" type="text" />
889
+ <input name="commit" type="submit" value="Create" />
890
+ </form>
891
+ ```
892
+
893
+ The params object created when this form is submitted would look like:
894
+
895
+ ```ruby
896
+ {"action" => "create", "controller" => "people", "person" => {"first_name" => "William", "last_name" => "Smith"}}
897
+ ```
898
+
899
+ The params hash has a nested person value, which can therefore be accessed with params[:person] in the controller.
900
+
901
+ #### check_box
902
+
903
+ Returns a checkbox tag tailored for accessing a specified attribute.
904
+
905
+ ```ruby
906
+ # Let's say that @article.validated? is 1:
907
+ check_box("article", "validated")
908
+ # => <input type="checkbox" id="article_validated" name="article[validated]" value="1" />
909
+ # <input name="article[validated]" type="hidden" value="0" />
910
+ ```
911
+
912
+ #### fields_for
913
+
914
+ Creates a scope around a specific model object like form_for, but doesn't create the form tags themselves. This makes fields_for suitable for specifying additional model objects in the same form:
915
+
916
+ ```html+erb
917
+ <%= form_for @person, url: {action: "update"} do |person_form| %>
918
+ First name: <%= person_form.text_field :first_name %>
919
+ Last name : <%= person_form.text_field :last_name %>
920
+
921
+ <%= fields_for @person.permission do |permission_fields| %>
922
+ Admin? : <%= permission_fields.check_box :admin %>
923
+ <% end %>
924
+ <% end %>
925
+ ```
926
+
927
+ #### file_field
928
+
929
+ Returns a file upload input tag tailored for accessing a specified attribute.
930
+
931
+ ```ruby
932
+ file_field(:user, :avatar)
933
+ # => <input type="file" id="user_avatar" name="user[avatar]" />
934
+ ```
935
+
936
+ #### form_for
937
+
938
+ Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields.
939
+
940
+ ```html+erb
941
+ <%= form_for @article do |f| %>
942
+ <%= f.label :title, 'Title' %>:
943
+ <%= f.text_field :title %><br>
944
+ <%= f.label :body, 'Body' %>:
945
+ <%= f.text_area :body %><br>
946
+ <% end %>
947
+ ```
948
+
949
+ #### hidden_field
950
+
951
+ Returns a hidden input tag tailored for accessing a specified attribute.
952
+
953
+ ```ruby
954
+ hidden_field(:user, :token)
955
+ # => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
956
+ ```
957
+
958
+ #### label
959
+
960
+ Returns a label tag tailored for labelling an input field for a specified attribute.
961
+
962
+ ```ruby
963
+ label(:article, :title)
964
+ # => <label for="article_title">Title</label>
965
+ ```
966
+
967
+ #### password_field
968
+
969
+ Returns an input tag of the "password" type tailored for accessing a specified attribute.
970
+
971
+ ```ruby
972
+ password_field(:login, :pass)
973
+ # => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" />
974
+ ```
975
+
976
+ #### radio_button
977
+
978
+ Returns a radio button tag for accessing a specified attribute.
979
+
980
+ ```ruby
981
+ # Let's say that @article.category returns "rails":
982
+ radio_button("article", "category", "rails")
983
+ radio_button("article", "category", "java")
984
+ # => <input type="radio" id="article_category_rails" name="article[category]" value="rails" checked="checked" />
985
+ # <input type="radio" id="article_category_java" name="article[category]" value="java" />
986
+ ```
987
+
988
+ #### text_area
989
+
990
+ Returns a textarea opening and closing tag set tailored for accessing a specified attribute.
991
+
992
+ ```ruby
993
+ text_area(:comment, :text, size: "20x30")
994
+ # => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
995
+ # #{@comment.text}
996
+ # </textarea>
997
+ ```
998
+
999
+ #### text_field
1000
+
1001
+ Returns an input tag of the "text" type tailored for accessing a specified attribute.
1002
+
1003
+ ```ruby
1004
+ text_field(:article, :title)
1005
+ # => <input type="text" id="article_title" name="article[title]" value="#{@article.title}" />
1006
+ ```
1007
+
1008
+ #### email_field
1009
+
1010
+ Returns an input tag of the "email" type tailored for accessing a specified attribute.
1011
+
1012
+ ```ruby
1013
+ email_field(:user, :email)
1014
+ # => <input type="email" id="user_email" name="user[email]" value="#{@user.email}" />
1015
+ ```
1016
+
1017
+ #### url_field
1018
+
1019
+ Returns an input tag of the "url" type tailored for accessing a specified attribute.
1020
+
1021
+ ```ruby
1022
+ url_field(:user, :url)
1023
+ # => <input type="url" id="user_url" name="user[url]" value="#{@user.url}" />
1024
+ ```
1025
+
1026
+ ### FormOptionsHelper
1027
+
1028
+ Provides a number of methods for turning different kinds of containers into a set of option tags.
1029
+
1030
+ #### collection_select
1031
+
1032
+ Returns `select` and `option` tags for the collection of existing return values of `method` for `object`'s class.
1033
+
1034
+ Example object structure for use with this method:
1035
+
1036
+ ```ruby
1037
+ class Article < ActiveRecord::Base
1038
+ belongs_to :author
1039
+ end
1040
+
1041
+ class Author < ActiveRecord::Base
1042
+ has_many :articles
1043
+ def name_with_initial
1044
+ "#{first_name.first}. #{last_name}"
1045
+ end
1046
+ end
1047
+ ```
1048
+
1049
+ Sample usage (selecting the associated Author for an instance of Article, `@article`):
1050
+
1051
+ ```ruby
1052
+ collection_select(:article, :author_id, Author.all, :id, :name_with_initial, {prompt: true})
1053
+ ```
1054
+
1055
+ If `@article.author_id` is 1, this would return:
1056
+
1057
+ ```html
1058
+ <select name="article[author_id]">
1059
+ <option value="">Please select</option>
1060
+ <option value="1" selected="selected">D. Heinemeier Hansson</option>
1061
+ <option value="2">D. Thomas</option>
1062
+ <option value="3">M. Clark</option>
1063
+ </select>
1064
+ ```
1065
+
1066
+ #### collection_radio_buttons
1067
+
1068
+ Returns `radio_button` tags for the collection of existing return values of `method` for `object`'s class.
1069
+
1070
+ Example object structure for use with this method:
1071
+
1072
+ ```ruby
1073
+ class Article < ActiveRecord::Base
1074
+ belongs_to :author
1075
+ end
1076
+
1077
+ class Author < ActiveRecord::Base
1078
+ has_many :articles
1079
+ def name_with_initial
1080
+ "#{first_name.first}. #{last_name}"
1081
+ end
1082
+ end
1083
+ ```
1084
+
1085
+ Sample usage (selecting the associated Author for an instance of Article, `@article`):
1086
+
1087
+ ```ruby
1088
+ collection_radio_buttons(:article, :author_id, Author.all, :id, :name_with_initial)
1089
+ ```
1090
+
1091
+ If `@article.author_id` is 1, this would return:
1092
+
1093
+ ```html
1094
+ <input id="article_author_id_1" name="article[author_id]" type="radio" value="1" checked="checked" />
1095
+ <label for="article_author_id_1">D. Heinemeier Hansson</label>
1096
+ <input id="article_author_id_2" name="article[author_id]" type="radio" value="2" />
1097
+ <label for="article_author_id_2">D. Thomas</label>
1098
+ <input id="article_author_id_3" name="article[author_id]" type="radio" value="3" />
1099
+ <label for="article_author_id_3">M. Clark</label>
1100
+ ```
1101
+
1102
+ #### collection_check_boxes
1103
+
1104
+ Returns `check_box` tags for the collection of existing return values of `method` for `object`'s class.
1105
+
1106
+ Example object structure for use with this method:
1107
+
1108
+ ```ruby
1109
+ class Article < ActiveRecord::Base
1110
+ has_and_belongs_to_many :authors
1111
+ end
1112
+
1113
+ class Author < ActiveRecord::Base
1114
+ has_and_belongs_to_many :articles
1115
+ def name_with_initial
1116
+ "#{first_name.first}. #{last_name}"
1117
+ end
1118
+ end
1119
+ ```
1120
+
1121
+ Sample usage (selecting the associated Authors for an instance of Article, `@article`):
1122
+
1123
+ ```ruby
1124
+ collection_check_boxes(:article, :author_ids, Author.all, :id, :name_with_initial)
1125
+ ```
1126
+
1127
+ If `@article.author_ids` is [1], this would return:
1128
+
1129
+ ```html
1130
+ <input id="article_author_ids_1" name="article[author_ids][]" type="checkbox" value="1" checked="checked" />
1131
+ <label for="article_author_ids_1">D. Heinemeier Hansson</label>
1132
+ <input id="article_author_ids_2" name="article[author_ids][]" type="checkbox" value="2" />
1133
+ <label for="article_author_ids_2">D. Thomas</label>
1134
+ <input id="article_author_ids_3" name="article[author_ids][]" type="checkbox" value="3" />
1135
+ <label for="article_author_ids_3">M. Clark</label>
1136
+ <input name="article[author_ids][]" type="hidden" value="" />
1137
+ ```
1138
+
1139
+ #### country_options_for_select
1140
+
1141
+ Returns a string of option tags for pretty much any country in the world.
1142
+
1143
+ #### country_select
1144
+
1145
+ Returns select and option tags for the given object and method, using country_options_for_select to generate the list of option tags.
1146
+
1147
+ #### option_groups_from_collection_for_select
1148
+
1149
+ Returns a string of `option` tags, like `options_from_collection_for_select`, but groups them by `optgroup` tags based on the object relationships of the arguments.
1150
+
1151
+ Example object structure for use with this method:
1152
+
1153
+ ```ruby
1154
+ class Continent < ActiveRecord::Base
1155
+ has_many :countries
1156
+ # attribs: id, name
1157
+ end
1158
+
1159
+ class Country < ActiveRecord::Base
1160
+ belongs_to :continent
1161
+ # attribs: id, name, continent_id
1162
+ end
1163
+ ```
1164
+
1165
+ Sample usage:
1166
+
1167
+ ```ruby
1168
+ option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
1169
+ ```
1170
+
1171
+ Possible output:
1172
+
1173
+ ```html
1174
+ <optgroup label="Africa">
1175
+ <option value="1">Egypt</option>
1176
+ <option value="4">Rwanda</option>
1177
+ ...
1178
+ </optgroup>
1179
+ <optgroup label="Asia">
1180
+ <option value="3" selected="selected">China</option>
1181
+ <option value="12">India</option>
1182
+ <option value="5">Japan</option>
1183
+ ...
1184
+ </optgroup>
1185
+ ```
1186
+
1187
+ Note: Only the `optgroup` and `option` tags are returned, so you still have to wrap the output in an appropriate `select` tag.
1188
+
1189
+ #### options_for_select
1190
+
1191
+ Accepts a container (hash, array, enumerable, your type) and returns a string of option tags.
1192
+
1193
+ ```ruby
1194
+ options_for_select([ "VISA", "MasterCard" ])
1195
+ # => <option>VISA</option> <option>MasterCard</option>
1196
+ ```
1197
+
1198
+ Note: Only the `option` tags are returned, you have to wrap this call in a regular HTML `select` tag.
1199
+
1200
+ #### options_from_collection_for_select
1201
+
1202
+ Returns a string of option tags that have been compiled by iterating over the `collection` and assigning the result of a call to the `value_method` as the option value and the `text_method` as the option text.
1203
+
1204
+ ```ruby
1205
+ # options_from_collection_for_select(collection, value_method, text_method, selected = nil)
1206
+ ```
1207
+
1208
+ For example, imagine a loop iterating over each person in @project.people to generate an input tag:
1209
+
1210
+ ```ruby
1211
+ options_from_collection_for_select(@project.people, "id", "name")
1212
+ # => <option value="#{person.id}">#{person.name}</option>
1213
+ ```
1214
+
1215
+ Note: Only the `option` tags are returned, you have to wrap this call in a regular HTML `select` tag.
1216
+
1217
+ #### select
1218
+
1219
+ Create a select tag and a series of contained option tags for the provided object and method.
1220
+
1221
+ Example:
1222
+
1223
+ ```ruby
1224
+ select("article", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, {include_blank: true})
1225
+ ```
1226
+
1227
+ If `@article.person_id` is 1, this would become:
1228
+
1229
+ ```html
1230
+ <select name="article[person_id]">
1231
+ <option value=""></option>
1232
+ <option value="1" selected="selected">David</option>
1233
+ <option value="2">Sam</option>
1234
+ <option value="3">Tobias</option>
1235
+ </select>
1236
+ ```
1237
+
1238
+ #### time_zone_options_for_select
1239
+
1240
+ Returns a string of option tags for pretty much any time zone in the world.
1241
+
1242
+ #### time_zone_select
1243
+
1244
+ Returns select and option tags for the given object and method, using `time_zone_options_for_select` to generate the list of option tags.
1245
+
1246
+ ```ruby
1247
+ time_zone_select( "user", "time_zone")
1248
+ ```
1249
+
1250
+ #### date_field
1251
+
1252
+ Returns an input tag of the "date" type tailored for accessing a specified attribute.
1253
+
1254
+ ```ruby
1255
+ date_field("user", "dob")
1256
+ ```
1257
+
1258
+ ### FormTagHelper
1259
+
1260
+ Provides a number of methods for creating form tags that don't rely on an Active Record object assigned to the template like FormHelper does. Instead, you provide the names and values manually.
1261
+
1262
+ #### check_box_tag
1263
+
1264
+ Creates a check box form input tag.
1265
+
1266
+ ```ruby
1267
+ check_box_tag 'accept'
1268
+ # => <input id="accept" name="accept" type="checkbox" value="1" />
1269
+ ```
1270
+
1271
+ #### field_set_tag
1272
+
1273
+ Creates a field set for grouping HTML form elements.
1274
+
1275
+ ```html+erb
1276
+ <%= field_set_tag do %>
1277
+ <p><%= text_field_tag 'name' %></p>
1278
+ <% end %>
1279
+ # => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset>
1280
+ ```
1281
+
1282
+ #### file_field_tag
1283
+
1284
+ Creates a file upload field.
1285
+
1286
+ ```html+erb
1287
+ <%= form_tag({action:"post"}, multipart: true) do %>
1288
+ <label for="file">File to Upload</label> <%= file_field_tag "file" %>
1289
+ <%= submit_tag %>
1290
+ <% end %>
1291
+ ```
1292
+
1293
+ Example output:
1294
+
1295
+ ```ruby
1296
+ file_field_tag 'attachment'
1297
+ # => <input id="attachment" name="attachment" type="file" />
1298
+ ```
1299
+
1300
+ #### form_tag
1301
+
1302
+ Starts a form tag that points the action to an url configured with `url_for_options` just like `ActionController::Base#url_for`.
1303
+
1304
+ ```html+erb
1305
+ <%= form_tag '/articles' do %>
1306
+ <div><%= submit_tag 'Save' %></div>
1307
+ <% end %>
1308
+ # => <form action="/articles" method="post"><div><input type="submit" name="submit" value="Save" /></div></form>
1309
+ ```
1310
+
1311
+ #### hidden_field_tag
1312
+
1313
+ Creates a hidden form input field used to transmit data that would be lost due to HTTP's statelessness or data that should be hidden from the user.
1314
+
1315
+ ```ruby
1316
+ hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@'
1317
+ # => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" />
1318
+ ```
1319
+
1320
+ #### image_submit_tag
1321
+
1322
+ Displays an image which when clicked will submit the form.
1323
+
1324
+ ```ruby
1325
+ image_submit_tag("login.png")
1326
+ # => <input src="/images/login.png" type="image" />
1327
+ ```
1328
+
1329
+ #### label_tag
1330
+
1331
+ Creates a label field.
1332
+
1333
+ ```ruby
1334
+ label_tag 'name'
1335
+ # => <label for="name">Name</label>
1336
+ ```
1337
+
1338
+ #### password_field_tag
1339
+
1340
+ Creates a password field, a masked text field that will hide the users input behind a mask character.
1341
+
1342
+ ```ruby
1343
+ password_field_tag 'pass'
1344
+ # => <input id="pass" name="pass" type="password" />
1345
+ ```
1346
+
1347
+ #### radio_button_tag
1348
+
1349
+ Creates a radio button; use groups of radio buttons named the same to allow users to select from a group of options.
1350
+
1351
+ ```ruby
1352
+ radio_button_tag 'gender', 'male'
1353
+ # => <input id="gender_male" name="gender" type="radio" value="male" />
1354
+ ```
1355
+
1356
+ #### select_tag
1357
+
1358
+ Creates a dropdown selection box.
1359
+
1360
+ ```ruby
1361
+ select_tag "people", "<option>David</option>"
1362
+ # => <select id="people" name="people"><option>David</option></select>
1363
+ ```
1364
+
1365
+ #### submit_tag
1366
+
1367
+ Creates a submit button with the text provided as the caption.
1368
+
1369
+ ```ruby
1370
+ submit_tag "Publish this article"
1371
+ # => <input name="commit" type="submit" value="Publish this article" />
1372
+ ```
1373
+
1374
+ #### text_area_tag
1375
+
1376
+ Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions.
1377
+
1378
+ ```ruby
1379
+ text_area_tag 'article'
1380
+ # => <textarea id="article" name="article"></textarea>
1381
+ ```
1382
+
1383
+ #### text_field_tag
1384
+
1385
+ Creates a standard text field; use these text fields to input smaller chunks of text like a username or a search query.
1386
+
1387
+ ```ruby
1388
+ text_field_tag 'name'
1389
+ # => <input id="name" name="name" type="text" />
1390
+ ```
1391
+
1392
+ #### email_field_tag
1393
+
1394
+ Creates a standard input field of email type.
1395
+
1396
+ ```ruby
1397
+ email_field_tag 'email'
1398
+ # => <input id="email" name="email" type="email" />
1399
+ ```
1400
+
1401
+ #### url_field_tag
1402
+
1403
+ Creates a standard input field of url type.
1404
+
1405
+ ```ruby
1406
+ url_field_tag 'url'
1407
+ # => <input id="url" name="url" type="url" />
1408
+ ```
1409
+
1410
+ #### date_field_tag
1411
+
1412
+ Creates a standard input field of date type.
1413
+
1414
+ ```ruby
1415
+ date_field_tag "dob"
1416
+ # => <input id="dob" name="dob" type="date" />
1417
+ ```
1418
+
1419
+ ### JavaScriptHelper
1420
+
1421
+ Provides functionality for working with JavaScript in your views.
1422
+
1423
+ #### button_to_function
1424
+
1425
+ Returns a button that'll trigger a JavaScript function using the onclick handler. Examples:
1426
+
1427
+ ```ruby
1428
+ button_to_function "Greeting", "alert('Hello world!')"
1429
+ button_to_function "Delete", "if (confirm('Really?')) do_delete()"
1430
+ button_to_function "Details" do |page|
1431
+ page[:details].visual_effect :toggle_slide
1432
+ end
1433
+ ```
1434
+
1435
+ #### define_javascript_functions
1436
+
1437
+ Includes the Action Pack JavaScript libraries inside a single `script` tag.
1438
+
1439
+ #### escape_javascript
1440
+
1441
+ Escape carrier returns and single and double quotes for JavaScript segments.
1442
+
1443
+ #### javascript_tag
1444
+
1445
+ Returns a JavaScript tag wrapping the provided code.
1446
+
1447
+ ```ruby
1448
+ javascript_tag "alert('All is good')"
1449
+ ```
1450
+
1451
+ ```html
1452
+ <script>
1453
+ //<![CDATA[
1454
+ alert('All is good')
1455
+ //]]>
1456
+ </script>
1457
+ ```
1458
+
1459
+ #### link_to_function
1460
+
1461
+ Returns a link that will trigger a JavaScript function using the onclick handler and return false after the fact.
1462
+
1463
+ ```ruby
1464
+ link_to_function "Greeting", "alert('Hello world!')"
1465
+ # => <a onclick="alert('Hello world!'); return false;" href="#">Greeting</a>
1466
+ ```
1467
+
1468
+ ### NumberHelper
1469
+
1470
+ Provides methods for converting numbers into formatted strings. Methods are provided for phone numbers, currency, percentage, precision, positional notation, and file size.
1471
+
1472
+ #### number_to_currency
1473
+
1474
+ Formats a number into a currency string (e.g., $13.65).
1475
+
1476
+ ```ruby
1477
+ number_to_currency(1234567890.50) # => $1,234,567,890.50
1478
+ ```
1479
+
1480
+ #### number_to_human_size
1481
+
1482
+ Formats the bytes in size into a more understandable representation; useful for reporting file sizes to users.
1483
+
1484
+ ```ruby
1485
+ number_to_human_size(1234) # => 1.2 KB
1486
+ number_to_human_size(1234567) # => 1.2 MB
1487
+ ```
1488
+
1489
+ #### number_to_percentage
1490
+
1491
+ Formats a number as a percentage string.
1492
+
1493
+ ```ruby
1494
+ number_to_percentage(100, precision: 0) # => 100%
1495
+ ```
1496
+
1497
+ #### number_to_phone
1498
+
1499
+ Formats a number into a US phone number.
1500
+
1501
+ ```ruby
1502
+ number_to_phone(1235551234) # => 123-555-1234
1503
+ ```
1504
+
1505
+ #### number_with_delimiter
1506
+
1507
+ Formats a number with grouped thousands using a delimiter.
1508
+
1509
+ ```ruby
1510
+ number_with_delimiter(12345678) # => 12,345,678
1511
+ ```
1512
+
1513
+ #### number_with_precision
1514
+
1515
+ Formats a number with the specified level of `precision`, which defaults to 3.
1516
+
1517
+ ```ruby
1518
+ number_with_precision(111.2345) # => 111.235
1519
+ number_with_precision(111.2345, 2) # => 111.23
1520
+ ```
1521
+
1522
+ ### SanitizeHelper
1523
+
1524
+ The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements.
1525
+
1526
+ #### sanitize
1527
+
1528
+ This sanitize helper will HTML encode all tags and strip all attributes that aren't specifically allowed.
1529
+
1530
+ ```ruby
1531
+ sanitize @article.body
1532
+ ```
1533
+
1534
+ If either the :attributes or :tags options are passed, only the mentioned tags and attributes are allowed and nothing else.
1535
+
1536
+ ```ruby
1537
+ sanitize @article.body, tags: %w(table tr td), attributes: %w(id class style)
1538
+ ```
1539
+
1540
+ To change defaults for multiple uses, for example adding table tags to the default:
1541
+
1542
+ ```ruby
1543
+ class Application < Rails::Application
1544
+ config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td'
1545
+ end
1546
+ ```
1547
+
1548
+ #### sanitize_css(style)
1549
+
1550
+ Sanitizes a block of CSS code.
1551
+
1552
+ #### strip_links(html)
1553
+ Strips all link tags from text leaving just the link text.
1554
+
1555
+ ```ruby
1556
+ strip_links("<a href="http://rubyonrails.org">Ruby on Rails</a>")
1557
+ # => Ruby on Rails
1558
+ ```
1559
+
1560
+ ```ruby
1561
+ strip_links("emails to <a href="mailto:me@email.com">me@email.com</a>.")
1562
+ # => emails to me@email.com.
1563
+ ```
1564
+
1565
+ ```ruby
1566
+ strip_links('Blog: <a href="http://myblog.com/">Visit</a>.')
1567
+ # => Blog: Visit.
1568
+ ```
1569
+
1570
+ #### strip_tags(html)
1571
+
1572
+ Strips all HTML tags from the html, including comments.
1573
+ This uses the html-scanner tokenizer and so its HTML parsing ability is limited by that of html-scanner.
1574
+
1575
+ ```ruby
1576
+ strip_tags("Strip <i>these</i> tags!")
1577
+ # => Strip these tags!
1578
+ ```
1579
+
1580
+ ```ruby
1581
+ strip_tags("<b>Bold</b> no more! <a href='more.html'>See more</a>")
1582
+ # => Bold no more! See more
1583
+ ```
1584
+
1585
+ NB: The output may still contain unescaped '<', '>', '&' characters and confuse browsers.
1586
+
1587
+ ### CsrfHelper
1588
+
1589
+ Returns meta tags "csrf-param" and "csrf-token" with the name of the cross-site
1590
+ request forgery protection parameter and token, respectively.
1591
+
1592
+ ```html
1593
+ <%= csrf_meta_tags %>
1594
+ ```
1595
+
1596
+ NOTE: Regular forms generate hidden fields so they do not use these tags. More
1597
+ details can be found in the [Rails Security Guide](security.html#cross-site-request-forgery-csrf).
1598
+
1599
+ Localized Views
1600
+ ---------------
1601
+
1602
+ Action View has the ability render different templates depending on the current locale.
1603
+
1604
+ For example, suppose you have a `ArticlesController` with a show action. By default, calling this action will render `app/views/articles/show.html.erb`. But if you set `I18n.locale = :de`, then `app/views/articles/show.de.html.erb` will be rendered instead. If the localized template isn't present, the undecorated version will be used. This means you're not required to provide localized views for all cases, but they will be preferred and used if available.
1605
+
1606
+ You can use the same technique to localize the rescue files in your public directory. For example, setting `I18n.locale = :de` and creating `public/500.de.html` and `public/404.de.html` would allow you to have localized rescue pages.
1607
+
1608
+ Since Rails doesn't restrict the symbols that you use to set I18n.locale, you can leverage this system to display different content depending on anything you like. For example, suppose you have some "expert" users that should see different pages from "normal" users. You could add the following to `app/controllers/application.rb`:
1609
+
1610
+ ```ruby
1611
+ before_action :set_expert_locale
1612
+
1613
+ def set_expert_locale
1614
+ I18n.locale = :expert if current_user.expert?
1615
+ end
1616
+ ```
1617
+
1618
+ Then you could create special views like `app/views/articles/show.expert.html.erb` that would only be displayed to expert users.
1619
+
1620
+ You can read more about the Rails Internationalization (I18n) API [here](i18n.html).