The Rails 4 Way (2014)
Chapter 11. All About Helpers
“Thank you for helping Helpers Helping the Helpless. Your help was very… helpful!”
—Mrs. Duong in the movie The Weekenders
Throughout the book so far, we’ve already covered some of the helper methods provided by Rails to help you assemble the user interface of your web application. This chapter lists and explains all of the helper modules and their methods, followed by instructions on effectively creating your own helpers.
Note
This chapter is essentially reference material. Although every effort has been made to make it readable straight through, you will notice that coverage of Action View’s helper modules is arranged alphabetically, starting with ActiveModelHelper and ending with UrlHelper. Within each module’s section, the methods are broken up into logical groups whenever appropriate.
This chapter is published under the Creative Commons Attribution-ShareAlike 4.0 license, http://creativecommons.org/licenses/by-sa/4.0/
11.1 ActiveModelHelper
The ActiveModelHelper module contains helper methods for quickly creating forms from objects that follow Active Model conventions, starting with Active Record models. The form method is able to create an entire form for all the basic content types of a given record. However, it does not know how to assemble user-interface components for manipulating associations. Most Rails developers assemble their own forms from scratch using methods from FormHelper, instead of using this module. However, this module does contain some useful helper for reporting validation errors in your forms that you will use on a regular basis.
Note that since Rails 3, you must add the following gem to your Gemfile in order to use this module.
gem 'dynamic_form'
11.1.1 Reporting Validation Errors
The error_message_on and error_messages_for methods help you to add formatted validation error information to your templates in a consistent fashion.
11.1.1.1 error_message_on(object, method, *options)
Returns a div tag containing the error message attached to the specified method on the object, if one exists. It’s useful for showing validation errors inline next to the corresponding form field. The object argument of the method can be an actual object reference or a symbol corresponding to the name of an instance variable. The method should be a symbol corresponding to the name of the attribute on the object for which to render an error message.
The contents can be specialized with options for pre- and post-text and custom CSS class.
prepend_text: string
Fragment to prepend to error messages generated.
append_text: string
Fragment to append to error messages generated.
css_class: class_name
CSS class name for div generated wrapping the error message. Defaults to formError.
Use of this method is common when the user-interface requirements specify individual validation messages per input field of a form, as in the following real-life example:
1 .form_field
2 .field_label
3 %span.required *
4 %label First Name
5 .textual
6 = form.text_field :first_name
7 = form.error_message_on :first_name
As in the example, the error_message_on helper is most commonly accessed via the form block variable of form_for and its variants. When used via the form variable, you leave off the first argument (specifying the object) since it’s implied.
11.1.1.2 error_messages_for(*params)
Returns a div tag containing all of the error messages for all of the objects held in instance variables identified as parameters.
1 = form_for @person do |form|
2 = form.error_messages
3 .text-field
4 = form.label :name, "Name"
5 = form.text_field :name
As in the example, the error_message_for helper is most commonly accessed via the form block variable of form_for and its variants. When used via the form variable, it is called error_messages and you leave off the first argument (specifying the object) since it’s implied.
This method was used by Rails scaffolding before version 3, but rarely in real production applications. The Rails API documentation advises you to use this method’s implementation as inspiration to meet your own requirements:
This is a prepackaged presentation of the errors with embedded strings and a certain HTML structure. If what you need is significantly different from the default presentation, it makes plenty of sense to access the object.errors instance yourself and set it up. View the source of this method to see how easy it is.
We’ll go ahead and reproduce the source of the method here with the warning that you should not try to use it as inspiration unless you have a good grasp of Ruby! On the other hand, if you have time to study the way that this method is implemented, it will definitely teach you a lot about the way that Rails is implemented, which is its own distinctive flavor of Ruby.
1 def error_messages_for(*params)
2 options = params.extract_options!.symbolize_keys
3
4 objects = Array.wrap(options.delete(:object) || params).map do |object|
5 object = instance_variable_get("@#{object}") unless object.
6 respond_to?(:to_model)
7 object = convert_to_model(object)
8
9 if object.class.respond_to?(:model_name)
10 options[:object_name] ||= object.class.model_name.human.downcase
11 end
12
13 object
14 end
15
16 objects.compact!
17 count = objects.inject(0) { |sum, object| sum + object.errors.count }
18
19 unless count.zero?
20 html = {}
21 [:id, :class].each do |key|
22 if options.include?(key)
23 value = options[key]
24 html[key] = value unless value.blank?
25 else
26 html[key] = 'error_explanation'
27 end
28 end
29 options[:object_name] ||= params.first
30
31 I18n.with_options locale: options[:locale],
32 scope: [:activerecord, :errors, :template] do |locale|
33 header_message = if options.include?(:header_message)
34 options[:header_message]
35 else
36 locale.t :header, count: count,
37 model: options[:object_name].to_s.gsub('_', ' ')
38 end
39
40 message = options.include?(:message) ? options[:message] : locale.t(:body)
41
42 error_messages = objects.sum do |object|
43 object.errors.full_messages.map do |msg|
44 content_tag(:li, msg)
45 end
46 end.join.html_safe
47
48 contents = ''
49 contents << content_tag(options[:header_tag] ||
50 :h2, header_message) unless header_message.blank?
51 contents << content_tag(:p, message) unless message.blank?
52 contents << content_tag(:ul, error_messages)
53
54 content_tag(:div, contents.html_safe, html)
55 end
56 else
57 ''
58 end
59 end
Later on in the chapter we’ll talk extensively about writing your own helper methods.
11.1.2 Automatic Form Creation
The next couple of methods are used for automatic field creation. You can try using them too, but I suspect that their usefulness is somewhat limited in real applications.
11.1.2.1 form(name, options)
Returns an entire form with input tags and everything for a named model object. Here are the code examples given in the dynamic form API documentation, using a hypothetical Post object from a bulletin-board application as an example:
1 form("post")
2 # => <form action='/posts/create' method='post'>
3 # <p>
4 # <label for="post_title">Title</label><br />
5 # <input id="post_title" name="post[title]" size="30" type="text"
6 # value="Hello World" />
7 # </p>
8 # <p>
9 # <label for="post_body">Body</label><br />
10 # <textarea cols="40" id="post_body" name="post[body]"
11 # rows="20"></textarea>
12 # </p>
13 # <input name="commit" type="submit" value="Create" />
14 # </form>
Internally, the method calls record.persisted? to infer whether the action for the form should be create or update. It is possible to explicitly specify the action of the form (and the value of the submit button along with it) by using the :action option.
If you need the form to have its enctype set to multipart, useful for file uploads, set the options[:multipart] to true.
You can also pass in an :input_block option, using Ruby’s Proc.new idiom to create a new anonymous code block. The block you supply will be invoked for each content column of your model, and its return value will be inserted into the form.
1 form("entry", action: "sign",
2 input_block: Proc.new { |record, column|
3 "#{column.human_name}: #{input(record, column.name)}<br />"
4 })
5 # => <form action="/entries/sign" method="post">
6 # Message:
7 # <input id="entry_message" name="entry[message]" size="30"
8 # type="text" /><br />
9 # <input name="commit" type="submit" value="Sign" />
10 # </form>
That example’s builder block, as it is referred to in the dynamic_form API docs, uses the input helper method, which is also part of this module, and is covered in the next section of this chapter.
Finally, it’s also possible to add additional content to the form by giving the call to form a block, as in the following snippet:
1 form("entry", action: "sign") do |form|
2 form << content_tag("b", "Department")
3 form << collection_select("department", "id", @departments, "id", "name")
4 end
The block is yielded a string accumulator (named form in the example), to which you append any additional content that you want to appear between the main input fields and the submit tag.
11.1.2.2 input(name, method, options)
The appropriately named input method takes some identifying information, and automatically generates an HTML input tag based on an attribute of an Active Record model. Going back to the Post example used in the explanation of form, here is the code snippet given in the Rails API docs:
1 input("post", "title")
2 # => <input id="post_title" name="post[title]" size="30"
3 # type="text" value="Hello World" />
To quickly show you the types of input fields generated by this method, I’ll simply reproduce a portion of the code from the module itself:
1 def to_tag(options = {})
2 case column_type
3 when :string
4 field_type = @method_name.include?("password") ? "password" : "text"
5 to_input_field_tag(field_type, options)
6 when :text
7 to_text_area_tag(options)
8 when :integer, :float, :decimal
9 to_input_field_tag("text", options)
10 when :date
11 to_date_select_tag(options)
12 when :datetime, :timestamp
13 to_datetime_select_tag(options)
14 when :time
15 to_time_select_tag(options)
16 when :boolean
17 to_boolean_select_tag(options).html_safe
18 end
19 end
11.1.3 Customizing the Way Validation Errors Are Highlighted
By default, when Rails marks a field in your form that failed a validation check, it does so by wrapping that field in a div element, with the class name field_with_errors. This behavior is customizable, since it is accomplished via a Proc object stored as a configuration property of theActionView::Base class:
1 moduleActionView
2 classBase
3 cattr_accessor :field_error_proc
4 @@field_error_proc = Proc.new{ |html_tag, instance|
5 "<div class=\"field_with_errors\">#{html_tag}</div>".html_safe
6 }
7 end
8
9 ...
Armed with this knowledge, changing the validation error behavior is as simple as overriding Action View’s field_error_proc attribute with your own custom Proc. I would suggest doing so in an initializer file.
In Listing 11.1, I changed the setting so that the input fields with validation errors are prefixed with a red ERR message.
Listing 11.1: Custom validation error display
1 ActionView::Base.field_error_proc =
2 Proc.new do |html_tag,instance|
3 %(<div style="color:red">ERR</div>) + html_tag
4 end
It has been suggested by many people that it would have been a much better default solution to simply add a field_with_errors CSS class to the input tag itself, instead of wrapping it with an extra div tag. Indeed, that would have made many of our lives easier, since an extra div often breaks pixel-perfect layouts. However, since html_tag is already constructed at the time when the field_error_proc is invoked, it is not trivial to modify its contents.
11.2 AssetTagHelper
According to the Rails API docs, this module
Provides methods for generating HTML that links views to assets such as images, javascripts, stylesheets, and feeds. These methods do not verify the assets exist before linking to them:
The AssetTagHelper module includes some methods that you will use on a daily basis during active Rails development, particularly image_tag.
11.2.1 Head Helpers
Some of the helper methods in this module help you add content to the head element of your HTML document.
11.2.1.1 auto_discovery_link_tag(type = :rss, url_options = {}, tag_options = {})
Returns a link tag that browsers and news readers can use to autodetect an RSS or ATOM feed. The type can either be :rss (default) or :atom. Control the link options in url_for format using the url_options.
You can modify the link tag itself using the tag_options parameter:
:rel
Specify the relation of this link; defaults to "alternate".
:type
Override MIME type (such as "application/atom+xml") that Rails would otherwise generate automatically for you.
:title
Specify the title of the link; defaults to a capitalized type.
Here are examples of usages of auto_discovery_link_tag as shown in the Rails API docs:
1 auto_discovery_link_tag
2 # => <link rel="alternate" type="application/rss+xml" title="RSS"
3 # href="http://www.currenthost.com/controller/action" />
4
5 auto_discovery_link_tag(:atom)
6 # => <link rel="alternate" type="application/atom+xml" title="ATOM"
7 # href="http://www.currenthost.com/controller/action" />
8
9 auto_discovery_link_tag(:rss, {action: "feed"})
10 # => <link rel="alternate" type="application/rss+xml" title="RSS"
11 # href="http://www.currenthost.com/controller/feed" />
12
13 auto_discovery_link_tag(:rss, {action: "feed"}, {title: "My RSS"})
14 # => <link rel="alternate" type="application/rss+xml" title="My RSS"
15 # href="http://www.currenthost.com/controller/feed" />
11.2.1.2 favicon_link_tag(source='favicon.ico', options={})
Returns a link loading a favicon file. By default, Rails will set the icon to favicon.ico. You may specify a different file in the first argument.
The favicon_link_tag helper accepts an optional options hash that accepts the following:
:rel
Specify the relation of this link; defaults to ‘shortcut icon’
:type
Override the auto-generated mime type; defaults to ‘image/vnd.microsoft.icon’
1 favicon_link_tag '/myicon.ico'
2 # => <link href="/assets/favicon.ico" rel="shortcut icon"
3 # type="image/vnd.microsoft.icon" />
11.2.1.3 javascript_include_tag(*sources)
Returns a script tag for each of the sources provided. You can pass in the filename (the .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 their full path, relative to your document root.
1 javascript_include_tag "xmlhr"
2 # => <script src="/assets/xmlhr.js?1284139606"></script>
3
4 javascript_include_tag "common", "/elsewhere/cools"
5 # => <script src="/assets/common.js?1284139606"></script>
6 # <script src="/elsewhere/cools.js?1423139606"></script>
When the Asset Pipeline is enabled, passing the name of the manifest file as a source, will include all JavaScript or CoffeeScript files that are specified within the manifest.
javascript_include_tag "application"
Note By default, not including the .js extension to a JavaScript source will result in .js being suffixed to the filename. However, this does not play well with JavaScript templating languages, as they have extensions of their own. To rectify this, as of Rails 4.1, setting the option :extname to false will result in the javascript_include_tag helper to not append .js to the supplied source. javascript_include_tag 'templates.jst', extname: false # => <script src="/javascripts/templates.jst"></script> |
11.2.1.4 javascript_path(source, options = {})
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.
11.2.1.5 stylesheet_link_tag(*sources)
Returns a stylesheet link tag for the sources specified as arguments. If you don’t specify an extension, .css will be appended automatically. Just like other helper methods that take a variable number of arguments plus options, you can pass a hash of options as the last argument and they will be added as attributes to the tag.
1 stylesheet_link_tag "style"
2 # => <link href="/stylesheets/style.css" media="screen"
3 # rel="Stylesheet" type="text/css" />
4
5 stylesheet_link_tag "style", media: "all"
6 # => <link href="/stylesheets/style.css" media="all"
7 # rel="Stylesheet" type="text/css" />
8
9 stylesheet_link_tag "random.styles", "/css/stylish"
10 # => <link href="/stylesheets/random.styles" media="screen"
11 # rel="Stylesheet" type="text/css" />
12 # <link href="/css/stylish.css" media="screen"
13 # rel="Stylesheet" type="text/css" />
11.2.1.6 stylesheet_path(source)
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.
11.2.2 Asset Helpers
This module also contains a series of helper methods that generate asset-related markup. It’s important to generate asset tags dynamically, because often assets are either packaged together or served up from a different server source than your regular content. Asset helper methods also timestamp your asset source urls to prevent browser caching problems.
11.2.2.1 audio_path(source)
Computes the path to an audio asset in the public/audios directory, which you would have to add yourself to your Rails project since it’s not generated by default. Full paths from the document root will be passed through. Used internally by audio_tag to build the audio path.
11.2.2.2 audio_tag(source, options = {})
Returns an HTML 5 audio tag based on the source argument.
1 audio_tag("sound")
2 # => <audio src="/audios/sound" />
3
4 audio_tag("sound.wav")
5 # => <audio src="/audios/sound.wav" />
6
7 audio_tag("sound.wav", autoplay: true, controls: true)
8 # => <audio autoplay="autoplay" controls="controls" src="/audios/sound.wav" />
11.2.2.3 font_path(source, options = {})
Computes the path to a font asset in the app/assets/fonts directory, which you would have to add yourself to your Rails project since it’s not generated by default. Full paths from the document root (beginning with a “/”) will be passed through.
1 font_path("font.ttf") # => /assets/font.ttf
2 font_path("dir/font.ttf") # => /assets/dir/font.ttf
3 font_path("/dir/font.ttf") # => /dir/font.ttf
11.2.2.4 image_path(source)
Computes the path to an image asset in the app/assets/images directory. Full paths from the document root (beginning with a “/”) will be passed through. This method is used internally by image_tag to build the image path.
1 image_path("edit.png") # => /assets/edit.png
2 image_path("icons/edit.png") # => /images/icons/edit.png
3 image_path("/icons/edit.png") # => /icons/edit.png
Courtenay says… The image_tag method makes use of the image_path method that we cover later in the chapter. This helpful method determines the path to use in the tag. You can call a controller “image” and have it work as a resource, despite the seemingly conflicting name, because for its internal use, ActionView aliases the method to path_to_image. |
11.2.2.5 image_tag(source, options = {})
Returns an img tag for use in a template. The source parameter can be a full path or a file that exists in your images directory. You can add additional arbitrary attributes to the img tag using the options parameter. The following two options are treated specially:
:alt
If no alternate text is given, the filename part of the source is used, after being capitalized and stripping off the extension.
:size
Supplied as widthxheight so "30x45" becomes the attributes width="30" and height="45". The :size option will fail silently if the value is not in the correct format.
1 image_tag("icon.png")
2 # => <img src="/assets/icon.png" alt="Icon" />
3
4 image_tag("icon.png", size: "16x10", alt: "Edit Entry")
5 # => <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />
6
7 image_tag("/photos/dog.jpg", class: 'icon')
8 # => <img src="/photos/icon.gif" alt="Dog" class="icon"/>
11.2.2.6 video_path
Computes the path to a video asset in the public/videos directory, which you would have to add yourself to your Rails project since it’s not generated by default. Full paths from the document root will be passed through. Used internally by video_tag to build the video src path.
11.2.2.7 video_tag(sources, options = {})
Returns an HTML 5 video tag for the sources. If sources is a string, a single video tag will be returned. If sources is an array, a video tag with nested source tags for each source will be returned. The sources can be full paths or files that exists in your public videos directory.
You can add normal HTML video element attributes using the options hash. The options supports two additional keys for convenience and conformance:
:poster
Set an image (like a screenshot) to be shown before the video loads. The path is calculated using image_path
:size
Supplied as widthxheight in the same manner as image_tag. The :size option can also accept a stringified number, which sets both width and height to the supplied value.
1 video_tag("trailer")
2 # => <video src="/videos/trailer" />
3
4 video_tag("trailer.ogg")
5 # => <video src="/videos/trailer.ogg" />
6
7 video_tag("trail.ogg", controls: true, autobuffer: true)
8 # => <video autobuffer="autobuffer" controls="controls"
9 # src="/videos/trail.ogg" />
10
11 video_tag("trail.m4v", size: "16x10", poster: "screenshot.png")
12 # => <video src="/videos/trailer.m4v" width="16" height="10"
13 # poster="/images/screenshot.png" />
14
15 video_tag(["trailer.ogg", "trailer.flv"])
16 # => <video>
17 # <source src="trailer.ogg"/>
18 # <source src="trailer.flv"/>
19 # </video>
11.2.3 Using Asset Hosts
By default, Rails links to assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated asset server by setting ActionController::Base.asset_host in a configuration file, typically in config/environments/production.rb so that it doesn’t affect your development environment. For example, you’d define assets.example.com to be your asset host this way:
config.action_controller.asset_host = "assets.example.com"
The helpers we’ve covered take that into account when generating their markup:
1 image_tag("rails.png")
2 # => <img alt="Rails"
3 # src="http://assets.example.com/images/rails.png?1230601161" />
4
5 stylesheet_link_tag("application")
6 # => <link
7 # href="http://assets.example.com/stylesheets/application.css?1232285206"
8 # media="screen" rel="stylesheet" type="text/css" />
Browsers typically open at most two simultaneous connections to a single host, which means your assets often have to wait for other assets to finish downloading. You can alleviate this by using a %d wildcard in the asset_host. For example, "assets%d.example.com". If that wildcard is present Rails distributes asset requests among the corresponding four hosts “assets0.example.com”, …, “assets3.example.com”. With this trick browsers will open eight simultaneous connections rather than two.
1 image_tag("rails.png")
2 # => <img alt="Rails"
3 # src="http://assets0.example.com/images/rails.png?1230601161" />
4
5 stylesheet_link_tag("application")
6 # => <link
7 # href="http://assets2.example.com/stylesheets/application.css?1232285206"
8 # media="screen" rel="stylesheet" type="text/css" />
To do this, you can either setup four actual hosts, or you can use wildcard DNS to CNAME the wildcard to a single asset host. You can read more about setting up your DNS CNAME records from your hosting provider. Note that this technique is purely a browser performance optimization and is not meant for server load balancing. 40
Alternatively, you can exert more control over the asset host by setting asset_host to a proc like
config.action_controller.asset_host = Proc.new { |source|
"http://assets#{rand(2) + 1}.example.com"
}
The example generates http://assets1.example.com and http://assets2.example.com randomly. This option is useful for example if you need fewer/more than four hosts, custom host names, etc. As you see the proc takes a source parameter. That’s a string with the absolute path of the asset with any extensions and timestamps in place, for example /images/rails.png?1230601161.
1 config.action_controller.asset_host = Proc.new { |source|
2 if source.starts_with?('/images')
3 "http://images.example.com"
4 else
5 "http://assets.example.com"
6 end
7 }
8
9 image_tag("rails.png")
10 # => <img alt="Rails"
11 src="http://images.example.com/images/rails.png?1230601161" />
12
13 stylesheet_link_tag("application")
14 # => <link href="http://assets.example.com/stylesheets/application.css?1232285206"
15 media="screen" rel="stylesheet" type="text/css" />
Alternatively you may ask for a second parameter request, which is particularly useful for serving assets from an SSL-protected page. The example below disables asset hosting for HTTPS connections, while still sending assets for plain HTTP requests from asset hosts. If you don’t have SSL certificates for each of the asset hosts this technique allows you to avoid warnings in the client about mixed media.
1 ActionController::Base.asset_host = Proc.new { |source, request|
2 if request.ssl?
3 "#{request.protocol}#{request.host_with_port}"
4 else
5 "#{request.protocol}assets.example.com"
6 end
7 }
For easier testing and reuse, you can also implement a custom asset host object that responds to call and takes either one or two parameters just like the proc.
config.action_controller.asset_host = AssetHostingWithMinimumSsl.new(
"http://asset%d.example.com", "https://asset1.example.com"
)
11.2.4 For Plugins Only
A handful of class methods in AssetTagHelper relate to configuration and are intended for use in plugins.
· register_javascript_expansion
· register_stylesheet_expansion
11.3 AtomFeedHelper
Provides an atom_feed helper to aid in generating Atom feeds in Builder templates.
1 atom_feed do |feed|
2 feed.title("My great blog!")
3 feed.updated(@posts.first.created_at)
4
5 @posts.each do |post|
6 feed.entry(post) do |entry|
7 entry.title(post.title)
8 entry.content(post.body, type: 'html')
9
10 entry.author do |author|
11 author.name("DHH")
12 end
13 end
14 end
15 end
The options for atom_feed are:
:language
Defaults to "en-US".
:root_url
The HTML alternative that this feed is doubling for. Defaults to "/" on the current host.
:url
The URL for this feed. Defaults to the current URL.
:id
The id for this feed. Defaults to tag:#{request.host},#{options}:#{request.fullpath.split(".")}
:schema_date
The date at which the tag scheme for the feed was first used. A good default is the year you created the feed. See http://feedvalidator.org/docs/error/InvalidTAG.html for more information. If not specified, 2005 is used (as an “I don’t care” value).
:instruct
Hash of XML processing instructions in the form {target => {attribute => value, ...}} or {target => [{attribute => value, ...}, ]}
Other namespaces can be added to the root element:
1 atom_feed(
2 'xmlns:app' => 'http://www.w3.org/2007/app',
3 'xmlns:openSearch' => 'http://a9.com/-/spec/opensearch/1.1/'
4 ) do |feed|
5 feed.title("My great blog!")
6 feed.updated((@posts.first.created_at))
7 feed.tag!(openSearch:totalResults, 10)
8
9 @posts.each do |post|
10 feed.entry(post) do |entry|
11 entry.title(post.title)
12 entry.content(post.body, type: 'html')
13 entry.tag!('app:edited', Time.now)
14
15 entry.author do |author|
16 author.name("DHH")
17 end
18 end
19 end
20 end
The Atom spec defines five elements that may directly contain xhtml content if type: 'xhtml' is specified as an attribute:
· content
· rights
· title
· subtitle
· summary
If any of these elements contain xhtml content, this helper will take care of the needed enclosing div and an xhtml namespace declaration.
1 entry.summary type: 'xhtml' do |xhtml|
2 xhtml.p pluralize(order.line_items.count, "line item")
3 xhtml.p "Shipped to #{order.address}"
4 xhtml.p "Paid by #{order.pay_type}"
5 end
The atom_feed method yields an AtomFeedBuilder instance. Nested elements also yield AtomBuilder instances.
11.4 CacheHelper
This module contains helper methods related to caching fragments of a view. Fragment caching is useful when certain elements of an action change frequently or depend on complicated state, while other parts rarely change or can be shared among multiple parties. The boundaries of a fragment to be cached are defined within a view template using the cache helper method. The topic was covered in detail in the caching section of Chapter 17, “Caching and Performance”.
11.5 CaptureHelper
One of the great features of Rails views is that you are not limited to rendering a single flow of content. Along the way, you can define blocks of template code that should be inserted into other parts of the page during rendering using yield. The technique is accomplished via a pair of methods from the CaptureHelper module.
11.5.0.1 capture(&block)
The capture method lets you capture part of a template’s output (inside a block) and assign it to an instance variable. The value of that variable can subsequently be used anywhere else on the template.
1 - message_html = capture do
2 %div
3 This is a message
I don’t think that the capture method is that useful on its own in a template. It’s a lot more useful when you use it in your own custom helper methods. It gives you the ability to write your own helpers that grab template content wrapped using a block. We cover that technique later on in this chapter in the section “Writing Your Own Helpers.”
11.5.0.2 content_for(name, &block)
We mentioned the content_for method in Chapter 10, “Action View” in the section “Yielding Content.” It allows you to designate a part of your template as content for another part of the page. It works similarly to its sister method capture (in fact, it uses capture itself). Instead of returning the contents of the block provided to it, it stores the content to be retrieved using yield elsewhere in the template (or most commonly, in the surrounding layout).
A common example is to insert sidebar content into a layout. In the following example, the link will not appear in the flow of the view template. It will appear elsewhere in the template, wherever yield :navigation_sidebar appears.
1 - content_for :navigation_sidebar do
2 = link_to 'Detail Page', item_detail_path(item)
11.5.0.3 content_for?(name)
Using this method, you can check whether the template will ultimately yield any content under a particular name using the content_for helper method, so that you can make layout decisions earlier in the template. The following example clearly illustrates usage of this method, by altering the CSS class of the body element dynamically:
1 %body{class: content_for?(:right_col) ? 'one-column' : 'two-column'}
2 = yield
3 = yield :right_col
11.5.0.4 provide(name, content = nil, &block)
The provide helper method works the same way as content_for, except for when used with streaming. When streaming, provide flushes the current buffer straight back to the layout and stops looking for more contents.
If you want to concatenate multiple times to the same buffer when rendering a given template, you should use content_for instead.
11.6 CsrfHelper
The CsrfHelper module only contains one method, named csrf_meta_tags. Including it in the <head> section of your template will output meta tags “csrf-param” and “csrf-token” with the name of the cross-site request forgery protection parameter and token, respectively.
1 %head
2 = csrf_meta_tags
The meta tags “csrf-param” and “csrf-token” are used by Rails to generate dynamic forms that implement non-remote links with :method.
11.7 DateHelper
The DateHelper module is used primarily to create HTML select tags for different kinds of calendar data. It also features one of the longest-named helper methods, a beast peculiar to Rails, called distance_of_time_in_words_to_now.
Lark says…
I guess that helper method name was too much of a mouthful, since at some point it was aliased to time_ago_in_words.
11.7.1 The Date and Time Selection Helpers
The following methods help you create form field input tags dealing with date and time data. All of them are prepared for multi-parameter assignment to an Active Record object. That’s a fancy way of saying that even though they appear in the HTML form as separate input fields, when they are posted back to the server, it is understood that they refer to a single attribute of the model. That’s some Rails magic for you!
11.7.1.1 date_select(object_name, method, options = {}, html_options = {})
Returns a matched set of three select tags (one each for year, month, and day) preselected for accessing a specified date-based attribute (identified by the method parameter) on an object assigned to the template (identified by object_name).
It’s possible to tailor the selects through the options hash, which accepts all the keys that each of the individual select builders do (like :use_month_numbers for select_month).
The date_select method also takes :discard_year, :discard_month, and :discard_day options, which drop the corresponding select tag from the set of three. Common sense dictates that discarding the month select will also automatically discard the day select. If the day is omitted, but not the month, Rails will assume that the day should be the first of the month.
It’s also possible to explicitly set the order of the tags using the :order option with an array of symbols :year, :month, and :day in the desired order. Symbols may be omitted and the respective select tag is not included.
Passing disabled: true as part of the options will make elements inaccessible for change (see Listing 11.2).
Listing 11.2: Examples of date_select
1 date_select("post", "written_on")
2
3 date_select("post", "written_on", start_year: 1995,
4 use_month_numbers: true,
5 discard_day: true,
6 include_blank: true)
7
8 date_select("post", "written_on", order: [:day, :month, :year])
9
10 date_select("user", "birthday", order: [:month, :day])
If anything is passed in the html_options hash it will be applied to every select tag in the set.
11.7.1.2 datetime_select(object_name, method, options = {}, html_options = {})
Works exactly like date_select, except for the addition of hour and minute select tags. Seconds may be added with the option :include_seconds. Along with the addition of time information come additional discarding options: :discard_hour, :discard_minute, and :discard_seconds.
Setting the ampm option to true return hours in the AM/PM format.
1 datetime_select("post", "written_on")
2
3 datetime_select("post", "written_on", ampm: true)
11.7.1.3 time_select(object_name, method, options = {}, html_options = {})
Returns a set of select tags (one for hour, minute, and optionally second) pre-selected for accessing a specified time-based attribute (identified by method) on an object assigned to the template (identified by object_name). You can include the seconds by setting the :include_seconds option totrue.
As with datetime_select, setting ampm: true will result in hours displayed in the AM/PM format.
1 time_select("post", "sunrise")
2
3 time_select("post", "written_on", include_seconds: true)
4
5 time_select("game", "written_on", ampm: true)
11.7.2 The Individual Date and Time Select Helpers
Sometimes you need just a particular element of a date or time, and Rails obliges you with a comprehensive set of individual date and time select helpers. In contrast to the date and time helpers that we just looked at, the following helpers are not bound to an instance variable on the page. Instead, they all take a date or time Ruby object as their first parameter. (All of these methods have a set of common options, covered in the following subsection.)
11.7.2.1 select_date(date = Date.current, options = {}, html_options = {})
Returns a set of select tags (one each for year, month, and day) pre-selected with the date provided (or the current date). It’s possible to explicitly set the order of the tags using the :order option with an array of symbols :year, :month, and :day in the desired order.
select_date(started_at, order: [:year, :month, :day])
11.7.2.2 select_datetime(datetime = Time.current, options = {}, html_options = {})
Returns a set of select tags (one each for year, month, day, hour, and minute) pre-selected with the datetime. Optionally, setting the include_seconds: true option adds a seconds field. It’s also possible to explicitly set the order of the tags using the :order option with an array of symbols:year, :month, and :day, :hour, :minute, and :seconds in the desired order. You can also add character values for the :date_separator and :time_separator options to control visual display of the elements (they default to "/" and ":").
11.7.2.3 select_day(date, options = {}, html_options = {})
Returns a select tag with options for each of the days 1 through 31 with the current day selected. The date can also be substituted for a day value ranging from 1 to 31. If displaying days with a leading zero is your preference, setting the option use_two_digit_numbers to true will accomplish this.
1 select_day(started_at)
2
3 select_day(10)
4
5 select_day(5, use_two_digit_numbers: true)
By default, the field name defaults to day, but can be overridden using the :field_name option.
11.7.2.4 select_hour(datetime, options = {}, html_options = {})
Returns a select tag with options for each of the hours 0 through 23 with the current hour selected. The datetime parameter can be substituted with an hour number from 0 to 23. Setting the ampm option to true will result in hours displayed in the AM/PM format. By default, the field name defaults to hour, but can be overridden using the :field_name option.
11.7.2.5 select_minute(datetime, options = {}, html_options = {})
Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected. Also can return a select tag with options by minute_step from 0 through 59 with the 00 minute selected. The datetime parameter can be substituted by a seconds value of 0 to 59. By default, the field name defaults to minute, but can be overridden using the :field_name option.
11.7.2.6 select_month(date, options = {}, html_options = {})
Returns a select tag with options for each of the months January through December with the current month selected. By default, the month names are presented as user options in the drop-down selection and the month numbers (1 through 12) are used as values submitted to the server.
It’s also possible to use month numbers for the presentation instead of names, by setting use_month_numbers: true. To display month numbers with a leading zero, set option :use_two_digit_numbers to true. If you happen to want both numbers and names, set add_month_numbers: true. If you would prefer to show month names as abbreviations, set the :use_short_month option to true. Finally, if you want to use your own month names, set the value of the :use_month_names key in your options to an array of 12 month names.
1 # Will use keys like "January", "March"
2 select_month(Date.today)
3
4 # Will use keys like "1", "3"
5 select_month(Date.today, use_month_numbers: true)
6
7 # Will use keys like "1 - January", "3 - March"
8 select_month(Date.today, add_month_numbers: true)
9
10 # Will use keys like "Jan", "Mar"
11 select_month(Date.today, use_short_month: true)
12
13 # Will use keys like "Januar", "Marts"
14 select_month(Date.today, use_month_names: %w(Januar Februar
15 Marts ...))
By default, the field name defaults to month, but can be overridden using the :field_name option.
11.7.2.7 select_second(datetime, options = {}, html_options = {})
Returns a select tag with options for each of the seconds 0 through 59 with the current second selected. The datetime parameter can either be a DateTime object or a second given as a number. By default, the field name defaults to second, but can be overridden using the :field_name option.
11.7.2.8 select_time(datetime = Time.current, options = {}, html_options = {})
Returns a set of HTML select tags (one for hour and minute). You can set the :time_separator option to format the output. It’s possible to take an input for sections by setting option :include_seconds to true.
select_time(some_time, time_separator: ':', include_seconds: true)
11.7.2.9 select_year(date, options = {}, html_options = {})
Returns a select tag with options for each of the 5 years on each side of the current year, which is selected. The five-year radius can be changed using the :start_year and :end_year options. Both ascending and descending year lists are supported by making :start_year less than or greater than :end_year. The date parameter can either be a Date object or a year given as a number.
1 # ascending year values
2 select_year(Date.today, start_year: 1992, end_year: 2007)
3
4 # descending year values
5 select_year(Date.today, start_year: 2005, end_year: 1900)
By default, the field name defaults to year, but can be overridden using the :field_name option.
11.7.3 Common Options for Date Selection Helpers
All of the select-type methods share a number of common options that are as follows:
:discard_type
Set to true if you want to discard the type part of the select name. If set to true, the select_month method would use simply date (which can be overwritten using :prefix) instead of date[month].
:field_name: Allows you to override the natural name of a select tag (from day, minute, and so on).
:include_blank
Set to true if it should be possible to set an empty date.
:prefix
Overwrites the default prefix of date used for the names of the select tags. Specifying birthday would result in a name of birthday[month] instead of date[month] when passed to the select_month method.
:use_hidden
Set to true to embed the value of the datetime into the page as an HTML hidden input, instead of a select tag.
:disabled
Set to true if you want show the select fields as disabled.
:prompt
Set to true (for a generic prompt), a prompt string or a hash of prompt strings for :year, :month, :day, :hour, :minute and :second.
11.7.4 distance_in_time Methods with Complex Descriptive Names
Some distance_in_time methods have really long, complex descriptive names that nobody can ever remember without looking them up. Well, at least for the first dozen times or so you might not remember.
I find the following methods to be a perfect example of the Rails way when it comes to API design. Instead of going with a shorter and necessarily more cryptic alternative, the framework author decided to keep the name long and descriptive. It’s one of those cases where a nonprogrammer can look at your code and understand what it’s doing. Well, probably.
I also find these methods remarkable in that they are part of why people sometimes consider Rails part of the Web 2.0 phenomenon. What other web framework would include ways to humanize the display of timestamps?
11.7.4.1 distance_of_time_in_words(from_time, to_time = 0, include_seconds_or_options = {}, options = {}))
Reports the approximate distance in time between two Time, DateTime, or Date objects or integers as seconds. Set the include_seconds parameter to true if you want more detailed approximations when the distance is less than 1 minute. The easiest way to show what this method does is via examples:
>> from_time = Time.current
>> helper.distance_of_time_in_words(from_time, from_time + 50.minutes)
=> about 1 hour
>> helper.distance_of_time_in_words(from_time, from_time + 15.seconds)
=> less than a minute
>> helper.distance_of_time_in_words(from_time, from_time + 15.seconds,
include_seconds: true)
=> less than 20 seconds
>> helper.distance_of_time_in_words(from_time, 3.years.from_now)
=> about 3 years
The Rails API docs ask you to note that Rails calculates 1 year as 365.25 days.
11.7.4.2 distance_of_time_in_words_to_now(from_time, include_seconds_or_options = {})
Works exactly like distance_of_time_in_words except that the to_time is hard-coded to the current time. Usually invoked on created_at or updated_at attributes of your model, followed by the string ago in your template, as in the following example:
1 %strong= comment.user.name
2 %br
3 %small= "#{distance_of_time_in_words_to_now(review.created_at)} ago"
Note, this method is aliased to time_ago_in_words for those who prefer shorter method names.
11.7.5 time_tag(date_or_time, *args, &block)
Introduced in Rails 3.1, the time_tag returns an HTML5 time element for a given date or time. Using the semantic time_tag helper ensures that your date or times within your markup are in a machine-readable format. Setting the option pubdate to true will add the attribute to the tag, indicating that the date or time is a publishing date. The following examples show the output one can expect when using it:
1 time_tag(Date.current)
2 # => <time datetime="2013-08-13">August 13, 2013</time>
3
4 time_tag(Time.current)
5 # => <time datetime="2013-08-13T14:58:29Z">August 13, 2013 14:58</time>
6
7 time_tag(Time.current, pubdate: true)
8 # => <time datetime="2013-08-13T15:02:56Z" pubdate="pubdate">August 13, 2013 15:02</time>
9
10 = time_tag(Date.current) do
11 %strong Once upon a time
12 # => <time datetime="2013-08-13"><strong>Once upon a time</strong></time>
11.8 DebugHelper
The DebugHelper module only contains one method, named debug. Output it in your template, passing it an object that you want dumped to YAML and displayed in the browser inside PRE tags. Useful for debugging during development, but not much else.
11.9 FormHelper
The FormHelper module provides a set of methods for working with HTML forms, especially as they relate to Active Record model objects assigned to the template. Its methods correspond to each type of HTML input fields (such as text, password, select, and so on) available. When the form is submitted, the value of the input fields are bundled into the params that is passed to the controller.
There are two types of form helper methods. The types found in this module are meant to work specifically with Active Record model attributes, and the similarly named versions in the FormTagHelper module are not.
Note The form helper methods in this section can also be used with non Active Record models, as long as the model passes the Active Model Lint tests found in module ActiveModel::Lint::Tests. The easiest way to do this is to include the module mixin ActiveModel::Model to your class. |
11.9.1 Creating Forms for Models
The core method of this helper is called form_for, and we covered it to some extent in Chapter 3, “REST, Resources, and Rails”. The helper method yields a form object, on which you can invoke input helper methods, omitting their first argument. Usage of form_for leads to succinct form code:
1 = form_for offer do |f|
2 = f.label :version, 'Version'
3 = f.text_field :version
4 %br
5 = f.label :author, 'Author'
6 = f.text_field :author
The form_for block argument is a form builder object that carries the model. Thus, the idea is that:
= f.text_field :first_name
gets expanded to
= text_field :person, :first_name
If you want the resulting params hash posted to your controller to be named based on something other than the class name of the object you pass to form_for, you can pass an arbitrary symbol to the :as option:
= form_for person, as: :client do |f|
In that case, the following call to text_field
= f.text_field :first_name
would get expanded to
= text_field :client, :first_name, object: person
11.9.1.1 form_for Options
In any of its variants, the rightmost argument to form_for is an optional hash of options:
:url
The URL the form is submitted to. It takes the same fields you pass to url_for or link_to. In particular you may pass here a named route directly as well. Defaults to the current action.
:namespace
A namespace that will be prefixed with an underscore on the generated HTML id of the form.
:html
Optional HTML attributes for the form tag.
:builder
Optional form builder class (instead of ActionView::Helpers::FormBuilder)
11.9.1.2 Resource-oriented Style
The preferred way to use form_for is to rely on automated resource identification, which will use the conventions and named routes of that approach, instead of manually configuring the :url option.
For example, if post is an existing record to be edited, then the resource-oriented style:
= form_for post do |f|
is equivalent to
= form_for post, as: :post, url: post_path(post),
method: :patch, html: { class: "edit_post",
id: "edit_post_45" } do |f|
The form_for method also recognizes new records, by calling new? on the object you pass to it.
= form_for(Post.new) do |f|
expands to
= form_for post, as: :post, url: posts_path, html: { class: "new_post",
id: "new_post" } do |f|
The individual conventions can be overridden by supplying an object argument plus :url, :method, and/or :html options.
= form_for(post, url: super_post_path(post)) do |f|
You can create forms with namespaced routes by passing an array as the first argument, as in the following example, which would map to a admin_post_url:
= form_for([:admin, post]) do |f|
The example below is the equivalent (old-school) version of form_tag, which doesn’t use a yielded form object and explicitly names the object being used in the input fields:
1 = form_tag people_path do
2 .field
3 = label :person, :first_name
4 = text_field :person, :first_name
5 .field
6 = label :person, :last_name
7 = text_field :person, :last_name
8 .buttons
9 = submit_tag 'Create'
The first version has slightly less repetition (remember your DRY principle) and is almost always going to be more convenient as long as you’re rendering Active Record objects.
11.9.1.3 Variables Are Optional
If you explicitly specify the object name parameter for input fields rather than letting them be supplied by the form, keep in mind that it doesn’t have to match a live object instance in scope for the template. Rails won’t complain if the object is not there. It will simply put blank values in the resulting form.
11.9.1.4 Rails-Generated Form Conventions
The HTML generated by the form_for invocations in the preceding example is characteristic of Rails forms, and follows specific naming conventions.
In case you’re wondering, the authenticity_token hidden field with gibberish up near the top of the form has to do with protection against malicious Cross-Site Request Forgery (CSRF) attacks.
1 <form accept-charset="UTF-8" action="/people" method="post">
2 <div style="margin:0;padding:0;display:inline">
3 <input name="utf8" type="hidden" value="✓" />
4 <input name="authenticity_token" type="hidden"
5 value="afl+6u3J/2meoHtve69q+tD9gPc3/QUsHCqPh85Z4WU=" /></div>
6 <div class='field'>
7 <label for="person_first_name">First name</label>
8 <input id="person_first_name" name="person[first_name]" type="text" />
9 </div>
10 <div class='field'>
11 <label for="person_last_name">Last name</label>
12 <input id="person_last_name" name="person[last_name]" type="text" />
13 </div>
14 <div class='buttons'>
15 <input name="commit" type="submit" value="Create" />
16 </div>
17 </form>
When this form is submitted, the params hash will look like the following example (using the format reflected in your development log for every request):
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"afl+6u3J/2meoHtve69q+tD9gPc3/QUsHCqPh85Z4WU=",
"person"=>{"first_name"=>"William", "last_name"=>"Smith"},
"commit"=>"Create"}
As you can see, the params hash has a nested "person" value, which is accessed using params[:person] in the controller. That’s pretty fundamental Rails knowledge, and I’d be surprised if you didn’t know it already. I promise we won’t rehash much more basic knowledge after the following section.
11.9.1.5 Displaying Existing Values
If you were editing an existing instance of Person, that object’s attribute values would have been filled into the form. That’s also pretty fundamental Rails knowledge. What about if you want to edit a new model object instance, pre-populated with certain values? Do you have to pass the values as options to the input helper methods? No. Since the form helpers display the values of the model’s attributes, it would simply be a matter of initializing the object with the desired values in the controller, as follows:
1 # Using the gem decent exposure
2 expose(:person) do
3 if person_id = (params[:person_id] || params[:id])
4 Person.find(person_id)
5 else
6 # Set default values that you want to appear in the form
7 Person.new(first_name: 'First', last_name: 'Last')
8 end
9 end
Since you’re only using new, no record is persisted to the database, and your default values magically appear in the input fields.
11.9.2 How Form Helpers Get Their Values
A rather important lesson to learn about Rails form helper methods is that the value they display comes directly from the database prior to meddling by the developer. Unless you know what you’re doing, you may get some unexpected results if you try to override the values to be displayed in a form.
Let’s illustrate with a simple LineItem model, which has a decimal rate attribute (by merits of a rate column in its database table). We’ll override its implicit rate accessor with one of our own:
1 classLineItem < ActiveRecord::Base
2 def rate
3 "A RATE"
4 end
5 end
In normal situations, the overridden accessor is hiding access to the real rate attribute, as we can illustrate using the console.
>> li = LineItem.new
=> #<LineItem ...>
>> li.rate
=> "A RATE"
However, suppose you were to compose a form to edit line items using form helpers:
1 = form_for line_item do |f|
2 = f.text_field :rate
You would find that it works normally, as if that overridden rate accessor doesn’t exist. The fact is that Rails form helpers use special methods named attribute_before_type_cast (which are covered in Chapter 5, “Working With Active Record”, “Working with Active Record”). The preceding example would use the method rate_before_type_cast, and bypass the overriding method we defined.
11.9.3 Integrating Additional Objects in One Form
The fields_for helper method creates a scope around a specific model object like form_for, but doesn’t create the form tags themselves. Neither does it have an actual HTML representation as a div or fieldset. The fields_for method is suitable for specifying additional model objects in the same form, particularly associations of the main object being represented in the form.
11.9.3.1 Generic Examples
The following simple example represents a person and its associated permissions.
1 = form_for person do |f| %>
2 First name:
3 = f.text_field :first_name
4 Last name:
5 = f.text_field :last_name
6 .permissions
7 = fields_for person.permission do |permission_fields|
8 Admin?:
9 = permission_fields.check_box :admin
11.9.3.2 Nested Attributes Examples
When the object belonging to the current scope has a nested attribute writer for a certain attribute, fields_for will yield a new scope for that attribute. This allows you to create forms that set or change the attributes of a parent object and its associations in one go.
Nested attribute writers are normal setter methods named after an association. The most common way of defining these writers is either by declaring accepts_nested_attributes_for in a model definition or by defining a method with the proper name. For example: the attribute writer for the association :address is called address_attributes=.
Whether a one-to-one or one-to-many style form builder will be yielded depends on whether the normal reader method returns a single object or an array of objects. Consider a simple Ruby Person class which returns a single Address from its address reader method and responds to theaddress_attributes= writer method:
1 classPerson
2 def address
3 @address
4 end
5
6 def address_attributes=(attributes)
7 # Process the attributes hash
8 end
9 end
This model can now be used with a nested fields_for, like:
1 = form_for person do |f|
2 = f.fields_for :address do |address_fields|
3 Street:
4 = address_fields.text_field :street
5 Zip code:
6 = address_fields.text_field :zip_code
When address is already an association on a Person you can use accepts_nested_attributes_for to define the writer method for you, like:
1 classPerson < ActiveRecord::Base
2 has_one :address
3 accepts_nested_attributes_for :address
4 end
If you want to destroy the associated model through the form, you have to enable it first using the :allow_destroy option for accepts_nested_attributes_for like:
1 classPerson < ActiveRecord::Base
2 has_one :address
3 accepts_nested_attributes_for :address, allow_destroy: true
4 end
Now, when you use a checkbox form element specially named _destroy, with a value that evaluates to true, the logic generated by accepts_nested_attribute_for will destroy the associated model. (This is a super useful technique for list screens that allow deletion of multiple records at once using checkboxes.)
1 = form_for person do |f|
2 = f.fields_for :address do |address_fields|
3 Delete this address:
4 = address_fields.check_box :_destroy
11.9.3.3 fields_for with One-to-Many Associations
Consider a Person class which returns an array of Project instances from the projects reader method and responds to the projects_attributes= writer method:
1 classPerson < ActiveRecord::Base
2 def projects
3 [@project1, @project2]
4 end
5
6 def projects_attributes=(attributes)
7 # Process the attributes hash
8 end
9 end
This model can now be used with a nested fields_for helper method in a form. The block given to the nested fields_for call will be repeated for each instance in the collection automatically:
1 = form_for person do |f|
2 = f.fields_for :projects do |project_fields|
3 .project
4 Name:
5 = project_fields.text_field :name
It’s also possible to specify the instance to be used by doing the iteration yourself. The symbol passed to fields_for refers to the reader method of the parent object of the form, but the second argument contains the actual object to be used for fields:
1 = form_for person do |f|
2 - person.projects.select(&:active?).each do |project|
3 = f.fields_for :projects, project do |project_fields|
4 .project
5 Name:
6 = project_fields.text_field :name
Since fields_for also understands a collection as its second argument in that situation, you can shrink that last example to the following code. Just inline the projects collection:
1 = form_for person do |f|
2 = f.fields_for :projects, projects.select(&:active?) do |project_fields|
3 .project
4 Name:
5 = project_fields.text_field :name
If in our example Person was an Active Record model and projects was one of its has_many associations, then you could use accepts_nested_attributes_for to define the writer method for you:
1 classPerson < ActiveRecord::Base
2 has_many :projects
3 accepts_nested_attributes_for :projects
4 end
As with using accepts_nested_attributes_for with a belongs_to association, if you want to destroy any of the associated models through the form, you have to enable it first using the :allow_destroy option:
1 classPerson < ActiveRecord::Base
2 has_many :projects
3 accepts_nested_attributes_for :projects, allow_destroy: true
4 end
This will allow you to specify which models to destroy in the attributes hash by adding a boolean form element named _destroy
1 = form_for person do |form|
2 = form.fields_for :projects do |project_fields|
3 Delete this project
4 = project_fields.check_box :_destroy
11.9.3.4 Saving Nested Attributes
Nested records are updated on save, even when the intermediate parent record is unchanged. For example, consider the following model code.
1 classProject < ActiveRecord::Base
2 has_many :tasks
3 accepts_nested_attributes_for :tasks
4 end
5
6 classTask < ActiveRecord::Base
7 belongs_to :project
8 has_many :assignments
9 accepts_nested_attributes_for :assignments
10 end
11
12 classAssignment < ActiveRecord::Base
13 belongs_to :task
14 end
The following spec snippet illustrates nested saving:
1 # setup project, task and assignment objects...
2 project.update(name: project.name,
3 tasks_attributes: [{
4 id: task.id,
5 name: task.name,
6 assignments_attributes: [
7 {
8 id: assignment.id,
9 name: 'Paul'
10 }]
11 }]
12
13 assignment.reload
14 expect(assignment.name).to eq('Paul')
11.9.4 Customized Form Builders
Under the covers, the form_for method uses a class named ActionView::Helpers::FormBuilder. An instance of it is yielded to the form block. Conveniently, you can subclass it in your application to override existing or define additional form helpers.
For example, let’s say you made a builder class to automatically add labels to form inputs when text_field is called. You’d enable it with the :builder option like:
= form_for person, builder: LabelingFormBuilder do |f|
Instructions on making custom form builder classes would fill its own chapter, but one could view the source of some popular Rails form builders such as SimpleForm41 and formtasic42 to learn more.
11.9.5 Form Inputs
For each if these methods, there is a similarly named form builder method that omits the object_name parameter.
11.9.5.1 check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")
This helper gives you an extra hidden input field to ensure that a false value is passed even if the check box is unchecked.
check_box('timesheet', 'approved')
# => <input name="timesheet[approved]" type="hidden" value="0"/>
# <input checked="checked" type="checkbox" id="timesheet_approved"
# name="timesheet[approved]" value="1" />
11.9.5.2 color_field(object_name, method, options = {})
Creates a color input field, that allows setting of a color via hex values. The default value of a color_field is set to #000000
color_field(:car, :paint_color)
# => <input id="car_paint_color" name="car[paint_color]" type="color"
# value="#000000" />"
This method is otherwise identical to text_field.
11.9.5.3 date_field(object_name, method, options = {})
Creates a date input field. If an object is provided to the helper, it calls to_date on it to attempt setting the default value.
date_field(:person, :birthday)
# => <input id="person_birthday" name="person[birthday]" type="date" />
To override the default value, pass a string in the format YYYY-MM-DD to the option :value. This method is otherwise identical to text_field.
11.9.5.4 datetime_field(object_name, method, options = {})
Creates an input field of type “datetype”, which accepts time in UTC. If a DateTime or ActiveSupport::TimeWithZone instance is provided to the helper, it calls strftime with “%Y-%m-%dT%T.%L%z” on the object’s value to attempt setting a default value.
datetime_field(:post, :publish_at)
# => <input id="post_publish_at" name="post[publish_at]" type="datetime" />
The datetime_field accepts options :min, :max, which allow setting the minimum and maximum acceptable values respectively.
datetime_field(:invoice, :invoiced_on,
min: Time.current.beginning_of_year,
max: Time.current.end_of_year)
# => <input id="invoice_invoiced_on" max="2013-12-31T23:59:59.999+0000"
# min="2013-01-01T00:00:00.000+0000" name="invoice[invoiced_on]"
# type="datetime" />
To override the default value, pass a string in the format “%Y-%m-%dT%T.%L%z” to the option :value. This method is otherwise identical to text_field.
11.9.5.5 datetime_local_field(object_name, method, options = {})
Creates an input field of type “datetime-local”. This method is otherwise identical to datetime_field, except that the value used is local over UTC. If a DateTime or ActiveSupport::TimeWithZone instance is provided to the helper, it calls strftime with “%Y-%m-%dT%T” on the object’s value to attempt setting a default value.
11.9.5.6 email_field(object_name, method, options = {})
Creates an email input field. This method is otherwise identical to text_field.
11.9.5.7 file_field(object_name, method, options = {})
Creates a file upload field and automatically adds multipart: true to the enclosing form. See file_field_tag for details.
11.9.5.8 hidden_field(object_name, method, options = {})
Creates a hidden field, with parameters similar to text_field.
11.9.5.9 label(object_name, method, content_or_options = nil, options = nil, &block)
Creates a label tag with the for attribute pointed at the specified input field.
label('timesheet', 'approved')
# => <label for="timesheet_approved">Approved</label>
label('timesheet', 'approved', 'Approved?')
# => <label for="timesheet_approved">Approved?</label>
Many of us like to link labels to input fields by nesting. (Many would say that’s the correct usage of labels.) As of Rails 3 the label helper accepts a block so that nesting is possible and works as would be expected. As a result, instead of having to do this:
= f.label :terms, "<span>Accept #{link_to 'Terms', terms_path}</span>"
you can do the much more elegant and maintainable
= f.label :terms do
%span Accept #{link_to "Terms", terms_path}
11.9.5.10 month_field(object_name, method, options = {})
Creates an input field of type “month”, without any timezone information. A month is represented by four digits for the year, followed by a dash, and ending with two digits representing the month (ex.2013-08).
If a DateTime or ActiveSupport::TimeWithZone instance is provided to the helper, it calls strftime with “%Y-%m” on the object’s value to attempt setting a default value.
month_field(:user, :born_on)
# => <input id="user_born_on" name="user[born_on]" type="month" />
To override the default value, pass a string in the format “%Y-%m” to the option :value. This method is otherwise identical to datetime_field.
11.9.5.11 number_field(object_name, method, options = {})
Creates a number input field. This method is otherwise identical to text_field with the following additional options:
:min
The minimum acceptable value.
:max
The maximum acceptable value.
:in
A range specifying the :min and :max values.
:step
The acceptable value granularity.
11.9.5.12 password_field(object_name, method, options = {})
Creates a password input field. This method is otherwise identical to text_field, but renders with a nil value by default for security reasons. If you want to pre-populate the user’s password you can do something like
password_field(:user, :password, value: user.password)
11.9.5.13 radio_button(object_name, method, tag_value, options = {})
Creates a radio button input field. Make sure to give all of your radio button options user the same name so that the browser will consider them linked.
= radio_button(:post, :category, :rails)
= radio_button(:post, :category, :ruby)
11.9.5.14 range_field(object_name, method, options = {})
Creates a range input field. This method is otherwise identical to number_field.
11.9.5.15 search_field(object_name, method, options = {})
Creates a search input field. This method is otherwise identical to text_field.
11.9.5.16 telephone_field(object_name, method, options = {})
Creates a telephone input field. This method is otherwise identical to text_field and is aliased as phone_field.
11.9.5.17 submit(value = nil, options = {})
Creates a submit button with the text value as the caption. The option :disable_with can be used to provide a name for disabled versions of the submit button.
11.9.5.18 text_area(object_name, method, options = {})
Creates a multiline text input field (the textarea tag). The :size option lets you easily specify the dimensions of the text area, instead of having to resort to explicit :rows and :cols options.
text_area(:comment, :body, size: "25x10")
# => <textarea name="comment[body]" id="comment_body" cols="25" rows="10">
# </textarea>
11.9.5.19 text_field(object_name, method, options = {})
Creates a standard text input field.
11.9.5.20 time_field(object_name, method, options = {})
Creates an input field of type “time”. If a DateTime or ActiveSupport::TimeWithZone instance is provided to the helper, it calls strftime with “%T.%L” on the object’s value to attempt setting a default value.
time_field(:task, :started_at)
# => <input id="task_started_at" name="task[started_at]" type="time" />
To override the default value, pass a string in the format “%T.%L” to the option :value. This method is otherwise identical to datetime_field.
11.9.5.21 url_field(object_name, method, options = {})
Creates an input field of type “url”. This method is otherwise identical to text_field.
11.9.5.22 week_field(object_name, method, options = {})
Creates an input field of type “week”. If a DateTime or ActiveSupport::TimeWithZone instance is provided to the helper, it calls strftime with “%Y-W%W” on the object’s value to attempt setting a default value.
week_field(:task, :started_at)
# => <input id="task_started_at" name="task[started_at]" type="week" />
To override the default value, pass a string in the format “%Y-W%W” to the option :value. This method is otherwise identical to datetime_field.
11.10 FormOptionsHelper
The methods in the FormOptionsHelper module are all about helping you to work with HTML select elements, by giving you ways to turn collections of objects into option tags.
11.10.1 Select Helpers
The following methods help you to create select tags based on a pair of object and attribute identifiers.
11.10.1.1 collection_select(object, method, collection, value_method, text_method, options = {}, html_options = {})
Return both select and option tags for the given object and method using options_from_collection_for_select (also in this module) to generate the list of option tags from the collection parameter.
11.10.1.2 grouped_collection_select(object, method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})
Returns select, optgroup, and option tags for the given object and method using option_groups_from_collection_for_select (covered later in this chapter ).
11.10.1.3 select(object, method, collection, value_method, text_method, options = {}, html_options = {})
Create a select tag and a series of contained option tags for the provided object and attribute. The value of the attribute currently held by the object (if any) will be selected, provided that the object is available (not nil). See options_for_select section for the required format of the choices parameter.
Here’s a small example where the value of @post.person_id is 1:
1 = select(:post, :person_id,
2 Person.all.collect { |p| [ p.name, p.id ] },
3 { include_blank: true })
Executing that helper code would generate the following HTML output:
1 <select id="post_person_id" name="post[person_id]">
2 <option value=""></option>
3 <option value="1" selected="selected">David</option>
4 <option value="2">Sam</option>
5 <option value="3">Tobias</option>
6 </select>
If necessary, specify selected: value to explicitly set the selection or selected: nil to leave all options unselected. The include_blank: true option inserts a blank option tag at the beginning of the list, so that there is no preselected value. Also, one can disable specific values by setting a single value or an array of values to the :disabled option.
11.10.1.4 time_zone_select(object, method, priority_zones = nil, options = {}, html_options = {})
Return select and option tags for the given object and method, using time_zone_options_for_select to generate the list of option tags.
In addition to the :include_blank option documented in the preceding section, this method also supports a :model option, which defaults to ActiveSupport::TimeZone. This may be used by users to specify a different timezone model object.
Additionally, setting the priority_zones parameter with an array of ActiveSupport::TimeZone objects, will list any specified priority time zones above any other.
1 time_zone_select(:user, :time_zone, [
2 ActiveSupport::TimeZone['Eastern Time (US & Canada)'],
3 ActiveSupport::TimeZone['Pacific Time (US & Canada)']
4 ])
5 # => <select id="user_time_zone" name="user[time_zone]">
6 # <option value="Eastern Time (US & Canada)">
7 # (GMT-05:00) Eastern Time (US & Canada)
8 # </option>
9 # <option value="Pacific Time (US & Canada)">
10 # (GMT-08:00) Pacific Time (US & Canada)
11 # </option>
12 # <option disabled="disabled" value="">-------------</option>
13 # <option value="American Samoa">(GMT-11:00) American Samoa</option>
14 # ...
Finally, setting the option :default to an instance of ActiveSupport::TimeZone, sets the default selected value if none was set.
11.10.2 Checkbox/Radio Helpers
The following methods create input tags of type “checkbox” or “radio” based on a collection.
11.10.2.1 collection_check_boxes(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
The form helper collection_check_boxes creates a collection of check boxes and associated labels based on a collection.
To illustrate, assuming we have a Post model that has multiple categories, using the collection_check_boxes helper, we can add the ability to set the category_ids of the post:
1 collection_check_boxes(:post, :category_ids, Category.all, :id, :name)
2 # => <input id="post_category_ids_1" name="post[category_ids][]"
3 # type="checkbox" value="1" />
4 # <label for="post_category_ids_1">Ruby on Rails</label>
5 # <input id="post_category_ids_2" name="post[category_ids][]"
6 # type="checkbox" value="2" />
7 # <label for="post_category_ids_2">Ruby</label>
8 # ...
If one wanted to change the way the labels and check boxes are rendered, passing a block will yield a builder:
1 collection_check_boxes(:post, :category_ids, Category.all,
2 :id, :name) do |item|
3 item.label(class: 'check-box') { item.check_box(class: 'check-box') }
4 end
The builder also has access to methods object, text and value of the current item being rendered.
11.10.2.2 collection_radio_buttons(object, method, collection, value_method, text_method, options = {}, html_options = {}, &block)
The form helper collection_radio_buttons creates a collection of radio buttons and associated labels based on a collection. It is predominately used to set an individual value, such as a belongs_to relationship on a model.
Kevin says…. Use collection_radio_buttons with a collection that only has a handful of items unless you want your page to be polluted with radio buttons. Fallback to a collection_select for a large collection. |
1 collection_radio_buttons(:post, :author_id, Author.all, :id, :name)
2 # => <input id="post_author_1" name="post[author_id][]"
3 # type="radio" value="1" />
4 # <label for="post_author_1">Obie</label>
5 # <input id="post_author_2" name="post[author_id][]"
6 # type="radio" value="2" />
7 # <label for="post_author_2">Kevin</label>
8 # ...
Similar to the collection_check_boxes helper, if one wanted to change the way the labels and radio buttons are rendered, passing a block will yield a builder:
1 collection_radio_buttons(:post, :author_id,
2 Author.all, :id, :name) do |item|
3 item.label(class: 'radio-button') {
4 item.radio_button(class: 'radio-button')
5 }
6 end
The builder also has access to methods object, text and value of the current item being rendered.
11.10.3 Option Helpers
For all of the following methods, only option tags are returned, so you have to invoke them from within a select helper or otherwise wrap them in a select tag.
11.10.3.1 grouped_options_for_select(grouped_options, selected_key = nil, options = {})
Returns a string of option tags, like options_for_select, but surrounds them with optgroup tags.
11.10.3.2 option_groups_from_collection_for_select(collection, group_method, group_label_method, option_key_method, option_value_method, selected_key = nil)
Returns a string of option tags, like options_from_collection_for_select, but surrounds them with optgroup tags. The collection should return a subarray of items when calling group_method on it. Each group in the collection should return its own name when calling group_label_method. The option_key_method and option_value_method parameters are used to calculate option tag attributes.
It’s probably much easier to show in an example than to explain in words.
option_groups_from_collection_for_select(@continents, :countries,
:continent_name, :country_id, :country_name, @selected_country.id)
This example could output the following HTML:
1 <optgroup label="Africa">
2 <option value="1">Egypt</option>
3 <option value="4">Rwanda</option>
4 ...
5 </optgroup>
6 <optgroup label="Asia">
7 <option value="3" selected="selected">China</option>
8 <option value="12">India</option>
9 <option value="5">Japan</option>
10 ...
11 </optgroup>
For the sake of clarity, here are the model classes reflected in the example:
1 classContinent
2 def initialize(name, countries)
3 @continent_name = name; @countries = countries
4 end
5
6 def continent_name
7 @continent_name
8 end
9
10 def countries
11 @countries
12 end
13 end
14
15 classCountry
16 def initialize(id, name)
17 @id, @name = id, name
18 end
19
20 def country_id
21 @id
22 end
23
24 def country_name
25 @name
26 end
27 end
11.10.3.3 options_for_select(container, selected = nil)
Accepts a container (hash, array, or anything else enumerable) and returns a string of option tags. Given a container where the elements respond to first and last (such as a two-element array), the “lasts” serve as option values and the “firsts” as option text. It’s not too hard to put together an expression that constructs a two-element array using the map and collect iterators.
For example, assume you have a collection of businesses to display, and you’re using a select field to allow the user to filter based on the category of the businesses. The category is not a simple string; in this example, it’s a proper model related to the business via a belongs_to association:
1 classBusiness < ActiveRecord::Base
2 belongs_to :category
3 end
4
5 classCategory < ActiveRecord::Base
6 has_many :businesses
7
8 def <=>(other)
9 ...
10 end
11 end
A simplified version of the template code for displaying that collection of businesses might look like:
- opts = businesses.map(&:category).collect { |c| [c.name, c.id] }
= select_tag(:filter, options_for_select(opts, params[:filter]))
The first line puts together the container expected by options_for_select by first aggregating the category attributes of the businesses collection using map and the nifty &:method syntax. The second line generates the select tag using those options (covered later in the chapter). Realistically you want to massage that category list a little more, so that it is ordered correctly and does not contain duplicates:
... businesses.map(&:category).uniq.sort.collect {...
Particularly with smaller sets of data, it’s perfectly acceptable to do this level of data manipulation in Ruby code. And of course, you probably don’t want to ever shove hundreds or especially thousands of rows in a select tag, making this technique quite useful. Remember to implement the spaceship method in your model if you need it to be sortable by the sort method.
Also, it’s worthwhile to experiment with eager loading in these cases, so you don’t end up with an individual database query for each of the objects represented in the select tag. In the case of our example, the controller would populate the businesses collection using code like:
expose(:businesses) do
Business.where(...).includes(:category)
end
Hashes are turned into a form acceptable to options_for_select automatically—the keys become firsts and values become lasts.
If selected parameter is specified (with either a value or array of values for multiple selections), the matching last or element will get the selected attribute:
1 options_for_select([["Dollar", "$"], ["Kroner", "DKK"]])
2 # => <option value="$">Dollar</option>
3 # <option value="DKK">Kroner</option>
4
5 options_for_select([ "VISA", "MasterCard" ], "MasterCard")
6 # => <option>VISA</option>
7 # <option selected="selected">MasterCard</option>
8
9 options_for_select({ "Basic" => "$20", "Plus" => "$40" }, "$40")
10 # => <option value="$20">Basic</option>
11 # <option value="$40" selected="selected">Plus</option>
12
13 >> options_for_select([ "VISA", "MasterCard", "Discover" ],
14 ["VISA", "Discover"])
15 # => <option selected="selected">VISA</option>
16 # <option>MasterCard</option>
17 # <option selected="selected">Discover</option>
A lot of people have trouble getting this method to correctly display their selected item. Make sure that the value you pass to selected matches the type contained in the object collection of the select; otherwise, it won’t work. In the following example, assuming price is a numeric value, without the to_s, selection would be broken, since the values passed as options are all strings:
1 options_for_select({ "Basic" => "20", "Plus" => "40" }, price.to_s)
2 # => <option value="20">Basic</option>
3 # <option value="40" selected="selected">Plus</option>
11.10.3.4 options_from_collection_for_select(collection, value_method, text_method, selected=nil)
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. If selected is specified, the element returning a match on value_method will get preselected.
1 options_from_collection_for_select(Person.all, :id, :name)
2 # => <option value="1">David</option>
3 <option value="2">Sam</option>
4 ...
11.10.3.5 time_zone_options_for_select(selected = nil, priority_zones = nil, model = ::ActiveSupport::TimeZone)
Returns a string of option tags for pretty much any timezone in the world. Supply a ActiveSupport::TimeZone name as selected to have it preselected. You can also supply an array of ActiveSupport::TimeZone objects as priority_zones, so that they will be listed above the rest of the (long) list. TimeZone.us_zones is a convenience method that gives you a list of the U.S. timezones only.
The selected parameter must be either nil, or a string that names a ActiveSupport::TimeZone (covered in the Appendix A, “ActiveSupport API Reference”).
11.11 FormTagHelper
The following helper methods generate HTML form and input tags based on explicit naming and values, contrary to the similar methods present in FormHelper, which require association to an Active Record model instance. All of these helper methods take an options hash, which may contain special options or simply additional attribute values that should be added to the HTML tag being generated.
11.11.0.1 button_tag(content_or_options = nil, options = nil, &block)
Creates a button element that can be used to define a submit, reset, or generic button to be used with JavaScript.
1 button_tag('Submit')
2 # => <button name="button" type="submit">Submit</button>
3
4 button_tag('Some call to action',type: 'button')
5 # => <button name="button" type="button">Some call to action</button>
11.11.0.2 check_box_tag(name, value = "1", checked = false, options = {})
Creates a check box input field. Unlike its fancier cousin, check_box in FormHelper, this helper does not give you an extra hidden input field to ensure that a false value is passed even if the check box is unchecked.
1 check_box_tag('remember_me')
2 # => <input id="remember_me" name="remember_me" type="checkbox" value="1"/>
3
4 check_box_tag('remember_me', 1, true)
5 # => <input checked="checked" id="remember_me" name="remember_me"
6 # type="checkbox" value="1" />
11.11.0.3 color_field_tag(name, value = nil, options = {})
Creates a color input field, that allows setting of a color via hex values. This method is otherwise identical to text_field_tag.
11.11.0.4 date_field_tag(name, value = nil, options = {})
Creates a date input field. This method is otherwise identical to text_field_tag.
11.11.0.5 datetime_field_tag(name, value = nil, options = {})
Creates a datetime input field, which accepts time in UTC. This method is otherwise identical to text_field_tag with the following additional options:
:min
The minimum acceptable value.
:max
The maximum acceptable value.
:step
The acceptable value granularity.
11.11.0.6 datetime_local_field_tag(name, value = nil, options = {})
Creates an input field of type “datetime-local”. This method is otherwise identical to datetime_field_tag, except that the value is not in UTC.
11.11.0.7 email_field_tag(name, value = nil, options = {})
Creates an email input field. This method is otherwise identical to text_field_tag.
11.11.0.8 field_set_tag(legend = nil, options = nil, &block)
Wrap the contents of the given block in a fieldset tag and optionally give it a legend tag.
11.11.0.9 file_field_tag(name, options = {})
Creates a file upload field. Remember to set your HTML form to multipart or file uploads will mysteriously not work:
1 = form_tag '/upload', multipart: true do
2 = label_tag :file, 'File to Upload'
3 = file_field_tag :file
4 = submit_tag
The controller action will receive a File object pointing to the uploaded file as it exists in a tempfile on your system. Processing of an uploaded file is beyond the scope of this book. If you’re smart, you’ll use Jonas Nicklas’ excellent CarrierWave gem instead of reinventing the wheel.43
11.11.0.10 form_tag(url_for_options = {}, options = {}, &block)
Starts a form tag, with its action attribute set to the URL passed as the url_for_options parameter.
The :method option defaults to POST. Browsers handle HTTP GET and POST natively; if you specify “patch,” “delete,” or any other HTTP verb is used, a hidden input field will be inserted with the name _method and a value corresponding to the method supplied. The Rails request dispatcher understands the _method parameter, which is the basis for the RESTful techniques you learned in Chapter 3, “REST, Resources, and Rails”.
The :multipart option allows you to specify that you will be including file-upload fields in the form submission and the server should be ready to handle those files accordingly.
The :authenticity_token option is used only if you need to pass a custom authenticity token string, or indicating not to include one at all by setting the option to false.
Setting the option :remote to true, will allow the Unobtrusive JavaScript drivers to take control of the submit behavior (Covered in chapter Ajax on Rails).
1 form_tag('/posts')
2 # => <form action="/posts" method="post">
3
4 >> form_tag('/posts/1', method: :patch)
5 # => <form action="/posts/1" method="post">
6 # <input name="_method" type="hidden" value="patch" />
7 # ...
8
9 form_tag('/upload', multipart: true)
10 # => <form action="/upload" method="post" enctype="multipart/form-data">
You might note that all parameters to form_tag are optional. If you leave them off, you’ll get a form that posts back to the URL that it came from—a quick and dirty solution that I use quite often when prototyping or experimenting. To quickly set up a controller action that handles post-backs, just include an if/else condition that checks the request method, something like:
1 def add
2 if request.post?
3 # handle the posted params
4 redirect_to :back
5 end
6 end
Notice that if the request is a post, I handle the form params and then redirect back to the original URL (using redirect_to :back). Otherwise, execution simply falls through and would render whatever template is associated with the action.
11.11.0.11 hidden_field_tag(name, value = nil, options = {})
Creates a hidden field, with parameters similar to text_field_tag.
11.11.0.12 image_submit_tag(source, options = {})
Displays an image that, when clicked, will submit the form. The interface for this method is the same as its cousin image_tag in the AssetTagHelper module.
Image input tags are popular replacements for standard submit tags, because they make an application look fancier. They are also used to detect the location of the mouse cursor on click—the params hash will include x and y data.
11.11.0.13 label_tag(name = nil, content_or_options = nil, options = nil, &block)
Creates a label tag with the for attribute set to name.
11.11.0.14 month_field_tag(name, value = nil, options = {})
Creates an input field of type “month”. This method is otherwise identical to text_field_tag with the following additional options:
:min
The minimum acceptable value.
:max
The maximum acceptable value.
:step
The acceptable value granularity.
11.11.0.15 number_field_tag(name, value = nil, options = {})
Creates a number input field. This method is otherwise identical to text_field_tag with the following additional options:
:min
The minimum acceptable value.
:max
The maximum acceptable value.
:in
A range specifying the :min and :max values
:step
The acceptable value granularity.
11.11.0.16 password_field_tag(name = "password", value = nil, options = {})
Creates a password input field. This method is otherwise identical to text_field_tag.
11.11.0.17 radio_button_tag(name, value, checked = false, options = {})
Creates a radio button input field. Make sure to give all of your radio button options the same name so that the browser will consider them linked.
11.11.0.18 range_field_tag(name, value = nil, options = {})
Creates a range input field. This method is otherwise identical to number_field_tag.
11.11.0.19 search_field_tag(name, value = nil, options = {})
Creates a search input field. This method is otherwise identical to text_field_tag.
11.11.0.20 select_tag(name, option_tags = nil, options = {})
Creates a drop-down selection box, or if the :multiple option is set to true, a multiple-choice selection box. The option_tags parameter is an actual string of option tags to put inside the select tag. You should not have to generate that string explicitly yourself. Instead, use the helpers inFormOptions (covered in the previous section of this chapter), which can be used to create common select boxes such as countries, time zones, or associated records.
11.11.0.21 submit_tag(value = "Save changes", options = {})
Creates a submit button with the text value as the caption. In conjunction with the unobtrusive JavaScript driver, one can set a :data attribute named :disable_with that can be used to provide a name for disabled versions of the submit button.
submit_tag('Save article', data: { disable_with: 'Please wait...' })
# => <input data-disable-with="Please wait..."
# name="commit" type="submit" value="Save article" />
11.11.0.22 telephone_field_tag(name, value = nil, options = {})
Creates a telephone input field. This method is otherwise identical to text_field_tag and is aliased as phone_field_tag.
11.11.0.23 text_area_tag(name, content = nil, options = {})
Creates a multiline text input field (the textarea tag). The :size option lets you easily specify the dimensions of the text area, instead of having to resort to explicit :rows and :cols options.
text_area_tag(:body, nil, size: "25x10")
# => <textarea name="body" id="body" cols="25" rows="10"></textarea>
11.11.0.24 text_field_tag(name, value = nil, options = {})
Creates a standard text input field.
11.11.0.25 time_field_tag(name, value = nil, options = {})
Creates an input field of type “time”. This method is otherwise identical to text_field_tag with the following additional options:
:min
The minimum acceptable value.
:max
The maximum acceptable value.
:step
The acceptable value granularity.
11.11.0.26 url_field_tag(name, value = nil, options = {})
Creates an input field of type “url”. This method is otherwise identical to text_field_tag.
11.11.0.27 utf8_enforcer_tag()
Creates the hidden UTF8 enforcer tag.
utf8_enforcer_tag
# => <input name="utf8" type="hidden" value="✓" />
11.11.0.28 week_field_tag(name, value = nil, options = {})
Creates an input field of type “week”. This method is otherwise identical to text_field_tag with the following additional options:
:min
The minimum acceptable value.
:max
The maximum acceptable value.
:step
The acceptable value granularity.
11.12 JavaScriptHelper
Provides helper methods to facilitate inclusion of JavaScript code in your templates.
11.12.0.1 escape_javascript(javascript)
Escapes line breaks, single and double quotes for JavaScript segments. It’s also aliased as j.
11.12.0.2 javascript_tag(content_or_options_with_block = nil, html_options = {}, &block)
Outputs a script tag with the content inside. The html_options are added as tag attributes.
11.13 NumberHelper
This module provides assistance in converting numeric data to formatted strings suitable for displaying in your view. Methods are provided for phone numbers, currency, percentage, precision, positional notation, and file size.
11.13.0.1 number_to_currency(number, options = {})
Formats a number into a currency string. You can customize the format in the options hash.
:locale
Sets the locale to be used for formatting, defaults to current locale.
:precision
Sets the level of precision, defaults to 2.
:unit
Sets the denomination of the currency, defaults to "$".
:separator
Sets the separator between the units, defaults to ".".
:delimiter
Sets the thousands delimiter, defaults to ",".
:format
Sets the format for non-negative numbers, defaults to "%u%n".
:negative_format
Sets the format for negative numbers, defaults to prepending an hyphen to the formatted number.
:raise
Setting to true raises InvalidNumberError when the number is invalid.
1 number_to_currency(1234567890.50)
2 # => $1,234,567,890.50
3
4 number_to_currency(1234567890.506)
5 # => $1,234,567,890.51
6
7 number_to_currency(1234567890.506, precision: 3)
8 # => $1,234,567,890.506
9
10 number_to_currency(1234567890.50, unit: "£", separator: ",",
11 delimiter: "")
12 # => £1234567890,50
11.13.0.2 number_to_human_size(number, options = {})
Formats a number that is more readable to humans. Useful for numbers that are extremely large. You can customize the format in the options hash.
:locale
Sets the locale to be used for formatting, defaults to current locale.
:precision
Sets the level of precision, defaults to 3.
:significant
If true, precision will be the number of significant_digits, otherwise the number of fractional digits are used. Defaults to true.
:separator
Sets the separator between fractional and integer digits, defaults to ".".
:delimiter
Sets the thousands delimiter, defaults to "".
:strip_insignificant_zeros
Setting to true removes insignificant zeros after the decimal separator, defaults to true.
:units
A hash of unit quantifier names, or a string containing an i18n scope where to find this hash. It might have the following keys:
· integers: :unit, :ten, *:hundred, :thousand, :million, *:billion, :trillion, *:quadrillion
· fractionals: :deci, :centi, *:mili, :micro, :nano, *:pico, :femto
:format
Sets the format for non-negative numbers, defaults to "%n %u". The field types are:
· %u: The quantifier
· %n: The number
1 number_to_human(123) # => "123"
2 number_to_human(1234) # => "1.23 Thousand"
3 number_to_human(1234567) # => "1.23 Million"
4 number_to_human(489939, precision: 4) # => "489.9 Thousand"
Kevin says… Rails provides the ability to set your own custom unit qualifier by setting the :units option. 1 number_to_human(10000, units: {unit: "m", thousand: "km"}) # => "10 km" |
11.13.0.3 number_to_human_size(number, options = {})
Formats the bytes in size into a more understandable representation. Useful for reporting file sizes to users. You can customize the format in the options hash.
:locale
Sets the locale to be used for formatting, defaults to current locale.
:precision
Sets the level of precision, defaults to 3.
:significant
If true, precision will be the number of significant_digits, otherwise the number of fractional digits are used. Defaults to true.
:separator
Sets the separator between fractional and integer digits, defaults to ".".
:delimiter
Sets the thousands delimiter, defaults to "".
:strip_insignificant_zeros
Setting to true removes insignificant zeros after the decimal separator, defaults to true.
:format
Sets the format for non-negative numbers, defaults to "%u%n".
:prefix
Setting to :si formats the number using the SI prefix, defaults to :binary.
:raise
Setting to true raises InvalidNumberError when the number is invalid.
1 number_to_human_size(123) => 123 Bytes
2 number_to_human_size(1234) => 1.21 KB
3 number_to_human_size(12345) => 12.1 KB
4 number_to_human_size(1234567) => 1.18 MB
5 number_to_human_size(1234567890) => 1.15 GB
6 number_to_human_size(1234567890123) => 1.12 TB
7 number_to_human_size(1234567, precision: 2) => 1.2 MB
11.13.0.4 number_to_percentage(number, options = {})
Formats a number as a percentage string. You can customize the format in the options hash.
:locale
Sets the locale to be used for formatting, defaults to current locale.
:precision
Sets the level of precision, defaults to 3
:significant
If true, precision will be the number of significant_digits, otherwise the number of fractional digits are used. Defaults to false.
:separator
Sets the separator between the units, defaults to "."
:delimiter
Sets the thousands delimiter, defaults to "".
:strip_insignificant_zeros
Setting to true removes insignificant zeros after the decimal separator, defaults to false.
:format
Sets the format of the percentage string, defaults to "%n%".
:raise
Setting to true raises InvalidNumberError when the number is invalid.
1 number_to_percentage(100) => 100.000%
2 number_to_percentage(100, precision: 0) => 100%
3 number_to_percentage(302.0574, precision: 2) => 302.06%
11.13.0.5 number_to_phone(number, options = {})
Formats a number as a U.S. phone number. You can customize the format in the options hash.
:area_code
Adds parentheses around the area code.
:delimiter
Specifies the delimiter to use, defaults to "-".
:extension
Specifies an extension to add to the end of the generated number.
:country_code
Sets the country code for the phone number.
:raise
Setting to true raises InvalidNumberError when the number is invalid.
1 number_to_phone(1235551234) # => "123-555-1234"
2 number_to_phone(1235551234, area_code: true) # => "(123) 555-1234"
3 number_to_phone(1235551234, delimiter: " ") # => "123 555 1234"
11.13.0.6 number_with_delimiter(number, options = {})
Formats a number with grouped thousands using a delimiter. You can customize the format in the options hash.
:locale
Sets the locale to be used for formatting, defaults to current locale.
:delimiter
Sets the thousands delimiter, defaults to ",".
:separator
Sets the separator between the units, defaults to ".".
:raise
Setting to true raises InvalidNumberError when the number is invalid.
1 number_with_delimiter(12345678) # => "12,345,678"
2 number_with_delimiter(12345678.05) # => "12,345,678.05"
3 number_with_delimiter(12345678, delimiter: ".") # => "12.345.678"
11.13.0.7 number_with_precision(number, options = {})
Formats a number with the specified level of precision. You can customize the format in the options hash.
:locale
Sets the locale to be used for formatting, defaults to current locale.
:precision
Sets the level of precision, defaults to 3
:significant
If true, precision will be the number of significant_digits, otherwise the number of fractional digits are used. Defaults to false.
:separator
Sets the separator between the units, defaults to "."
:delimiter
Sets the thousands delimiter, defaults to "".
:strip_insignificant_zeros
Setting to true removes insignificant zeros after the decimal separator, defaults to false.
:raise
Setting to true raises InvalidNumberError when the number is invalid.
1 number_with_precision(111.2345) # => "111.235"
2 number_with_precision(111.2345, precision: 2) # => "111.23"
11.14 OutputSafetyHelper
This is an extremely simple helper module, barely worth mentioning.
11.14.0.1 raw(stringish)
Bypasses HTML sanitization, by calling to_s, then html_safe on the argument passed to it.
11.14.0.2 safe_join(array, sep=$,)
Returns a HTML safe string by first escaping all array items and joining them by calling Array#join using the supplied separator. The returned string is also called with html_safe for good measure.
safe_join(["<p>foo</p>".html_safe, "<p>bar</p>"], "<br />")
# => "<p>foo</p><br /><p>bar</p>"
11.15 RecordTagHelper
This module assists in creation of HTML markup code that follows good, clean naming conventions.
11.15.0.1 content_tag_for(tag_name, single_or_multiple_records, prefix = nil, options = nil, &block)
This helper method creates an HTML element with id and class parameters that relate to the specified Active Record object. For instance, assuming @person is an instance of a Person class, with an id value of 123 then the following template code
= content_tag_for(:tr, @person) do
%td= @person.first_name
%td= @person.last_name
will produce the following HTML
<tr id="person_123" class="person">
...
</tr>
If you require the HTML id attribute to have a prefix, you can specify it as a third argument:
content_tag_for(:tr, @person, :foo) do ...
# => "<tr id="foo_person_123" class="person">..."
The content_tag_for helper also accepts a hash of options, which will be converted to additional HTML attributes on the tag. If you specify a :class value, it will be combined with the default class name for your object instead of replacing it (since replacing it would defeat the purpose of the method!).
content_tag_for(:tr, @person, :foo, class: 'highlight') do ...
# => "<tr id="foo_person_123" class="person highlight">..."
11.15.0.2 div_for(record, *args, &block)
Produces a wrapper div element with id and class parameters that relate to the specified Active Record object. This method is exactly like content_tag_for except that it’s hard-coded to output div elements.
11.16 RenderingHelper
This module contains helper methods related to rendering from a view context, to be used with an ActionView::Renderer object. Development of an Action View renderer is outside the scope of this book, but for those who are interested, investigating the source code forActionView::TemplateRenderer and ActionView::PartialRenderer would be a good starting point.44
11.17 SanitizeHelper
The SanitizeHelper module provides a set of methods for scrubbing text of undesired HTML elements. Rails sanitizes and escapes html content by default, so this helper is really intended to assist with the inclusion of dynamic content into your views.
11.17.0.1 sanitize(html, options = {})
Encodes all tags and strip all attributes (not specifically allowed) from the html string passed to it. Also strips href and src tags with invalid protocols, particularly in an effort to to prevent abuse of javascript attribute values.
= sanitize @article.body
With its default settings, the sanitize method does its best to counter known hacker tricks such as using unicode/ascii/hex values to get past the JavaScript filters.
You can customize the behavior of sanitize by adding or removing allowable tags and attributes using the :attributes or :tags options.
= sanitize @article.body, tags: %w(table tr td),
attributes: %w(id class style)
It’s possible to add tags to the default allowed tags in your application by altering the value of config.action_view.sanitized_allowed_tags in an initializer. For instance, the following code adds support for basic HTML tables.
1 classApplication < Rails::Application
2 config.action_view.sanitized_allowed_tags = 'table', 'tr', 'td'
3 end
You can also remove some of the tags that are allowed by default.
1 classApplication < Rails::Application
2 config.after_initialize do
3 ActionView::Base.sanitized_allowed_tags.delete 'div'
4 end
5 end
Or change them altogether.
1 classApplication < Rails::Application
2 config.action_view.sanitized_allowed_attributes = 'id', 'class', 'style'
3 end
Sanitizing user-provided text does not guarantee that the resulting markup will be valid (conforming to a document type) or even well-formed. The output may still contain unescaped <, >, & characters that confuse browsers and adversely affect rendering.
11.17.0.2 sanitize_css(style)
Sanitizes a block of CSS code. Used by sanitize when it comes across a style attribute in HTML being sanitized.
11.17.0.3 strip_links(html)
Strips all link tags from text leaving just the link text.
1 strip_links('<a href="http://www.rubyonrails.org">Ruby on Rails</a>')
2 # => Ruby on Rails
3
4 strip_links('Please email me at <a href="mailto:me@email.com">me@email.com</a>.')
5 # => Please email me at me@email.com.
6
7 strip_links('Blog: <a href="http://www.myblog.com/" class="nav">Visit</a>.')
8 # => Blog: Visit
11.17.0.4 strip_tags(html)
Strips all tags from the supplied HTML string, including comments. Its HTML parsing ability is limited by that of the html-scanner tokenizer built into Rails. 45
1 strip_tags("Strip <i>these</i> tags!")
2 # => Strip these tags!
3
4 strip_tags("<b>Bold</b> no more! <a href='more.html'>See more here</a>...")
5 # => Bold no more! See more here...
6
7 strip_tags("<div id='top-bar'>Welcome to my website!</div>")
8 # => Welcome to my website!
11.18 TagHelper
This module provides helper methods for generating HTML tags programmatically.
11.18.0.1 cdata_section(content)
Returns a CDATA section wrapping the given content. CDATA sections are used to escape blocks of text containing characters that would otherwise be recognized as markup. CDATA sections begin with the string <![CDATA[ and end with (and may not contain) the string ]]>.
11.18.0.2 content_tag(name, content_or_options_with_block = nil, options = nil, escape = true, &block)
Returns an HTML block tag of type name surrounding the content. Add HTML attributes by passing an attributes hash as options. Instead of passing the content as an argument, you can also use a block to hold additional markup (and/or additional calls to content_tag) in which case, you pass your options as the second parameter. Set escape to false to disable attribute value escaping.
Here are some simple examples of using content_tag without a block:
1 content_tag(:p, "Hello world!")
2 # => <p>Hello world!</p>
3
4 content_tag(:div, content_tag(:p, "Hello!"), class: "message")
5 # => <div class="message"><p>Hello!</p></div>
6
7 content_tag("select", options, multiple: true)
8 # => <select multiple="multiple">...options...</select>
Here it is with content in a block (shown as template code rather than in the console):
= content_tag :div, class: "strong" do
Hello world!
The preceding code produces the following HTML:
<div class="strong">Hello world!</div>
11.18.0.3 escape_once(html)
Returns an escaped version of HTML without affecting existing escaped entities.
1 escape_once("1 > 2 & 3")
2 # => "1 < 2 & 3"
3
4 escape_once("<< Accept & Checkout")
5 # => "<< Accept & Checkout"
11.18.0.4 tag(name, options = nil, open = false, escape = true)
Returns an empty HTML tag of type name, which by default is XHTML compliant. Setting open to true will create an open tag compatible with HTML 4.0 and below. Add HTML attributes by passing an attributes hash to options. Set escape to false to disable attribute value escaping.
The options hash is used with attributes with no value like (disabled and readonly), which you can give a value of true in the options hash. You can use symbols or strings for the attribute names.
1 tag("br")
2 # => <br />
3
4 tag("br", nil, true)
5 # => <br>
6
7 tag("input", type: 'text', disabled: true)
8 # => <input type="text" disabled="disabled" />
9
10 tag("img", src: "open.png")
11 # => <img src="open.png" />
11.19 TextHelper
The methods in this module provide filtering, formatting, and string transformation capabilities.
11.19.0.1 concat(string)
The preferred method of outputting text in your views is to use the = expression in Haml syntax, or the <%= expression %> in eRuby syntax. The regular puts and print methods do not operate as expected in an eRuby code block; that is, if you expected them to output to the browser. If you absolutely must output text within a non-output code block like - expression in Haml, or <% expression %> in eRuby, you can use the concat method. I’ve found that this method can be especially useful when combined with capture in your own custom helper method implementations.
The following example code defines a helper method that wraps its block content in a div with a particular CSS class.
1 def wrap(&block)
2 concat(content_tag(:div, capture(&block), class: "wrapped_content"))
3 end
You would use it in your template as follows:
1 - wrap do
2 My wrapped content
11.19.0.2 current_cycle(name = "default")
Returns the current cycle string after a cycle has been started. Useful for complex table highlighting or any other design need which requires the current cycle string in more than one place.
1 - # Alternate background colors with coordinating text color
2 - [1,2,3,4].each do |item|
3 %div(style="background-color:#{cycle('red', 'green', 'blue')}")
4 %span(style="color:dark#{current_cycle}")= item
11.19.0.3 cycle(first_value, *values)
Creates a Cycle object whose to_s method cycles through elements of the array of values passed to it, every time it is called. This can be used, for example, to alternate classes for table rows. Here’s an example that alternates CSS classes for even and odd numbers, assuming that the @itemsvariable holds an array with 1 through 4:
1 %table
2 - @items.each do |item|
3 %tr{ class: cycle('even', 'odd') }
4 %td= item
As you can tell from the example, you don’t have to store the reference to the cycle in a local variable or anything like that; you just call the cycle method repeatedly. That’s convenient, but it means that nested cycles need an identifier. The solution is to pass cycle a name: cycle_name option as its last parameter. Also, you can manually reset a cycle by calling reset_cycle and passing it the name of the cycle to reset. For example, here is some data to iterate over:
1 # Cycle CSS classes for rows, and text colors for values within each row
2 @items = [{first: 'Robert', middle: 'Daniel', last: 'James'},
3 {first: 'Emily', last: 'Hicks'},
4 {first: 'June', middle: 'Dae', last: 'Jones'}]
And here is the template code. Since the number of cells rendered varies, we want to make sure to reset the colors cycle before looping:
1 - @items.each do |item|
2 %tr{ class: cycle('even', 'odd', name: 'row_class') }
3 - item.values.each do |value|
4 %td{ class: cycle('red', 'green', name: 'colors') }
5 = value
6 - reset_cycle 'colors'
11.19.0.4 excerpt(text, phrase, options = {})
Extracts an excerpt from text that matches the first instance of phrase. The :radius option expands the excerpt on each side of the first occurrence of phrase by the number of characters defined in :radius (which defaults to 100). If the excerpt radius overflows the beginning or end of the text, the :omission option will be prepended/appended accordingly. Use the :separator option to set the delimitation. If the phrase isn’t found, nil is returned.
1 excerpt('This is an example', 'an', radius: 5)
2 # => "...s is an examp..."
3
4 excerpt('This is an example', 'is', radius: 5)
5 # => "This is an..."
6
7 excerpt('This is an example', 'is')
8 # => "This is an example"
9
10 excerpt('This next thing is an example', 'ex', radius: 2)
11 # => "...next..."
12
13 excerpt('This is also an example', 'an', radius: 8, omission: '<chop> ')
14 # => "<chop> is also an example"
11.19.0.5 highlight(text, phrases, options = {})
Highlights one or more phrases everywhere in text by inserting into a highlighter template. The highlighter can be specialized by passing the option :highlighter as a single-quoted string with \1 where the phrase is to be inserted.
1 highlight('You searched for: rails', 'rails')
2 # => You searched for: <mark>rails</mark>
3
4 highlight('You searched for: ruby, rails, dhh', 'actionpack')
5 # => You searched for: ruby, rails, dhh
6
7 highlight('You searched for: rails', ['for', 'rails'],
8 highlighter: '<em>\1</em>')
9 # => You searched <em>for</em>: <em>rails</em>
10
11 highlight('You searched for: rails', 'rails',
12 highlighter: '<a href="search?q=\1">\1</a>')
13 # => You searched for: <a href="search?q=rails">rails</a>
Note that as of Rails 4, the highlight helper now uses the HTML5 mark tag by default.
11.19.0.6 pluralize(count, singular, plural = nil)
Attempts to pluralize the singular word unless count is 1. If the plural is supplied, it will use that when count is > 1. If the ActiveSupport Inflector is loaded, it will use the Inflector to determine the plural form; otherwise, it will just add an “s” to the singular word.
1 pluralize(1, 'person')
2 # => 1 person
3
4 pluralize(2, 'person')
5 # => 2 people
6
7 pluralize(3, 'person', 'users')
8 # => 3 users
9
10 pluralize(0, 'person')
11 # => 0 people
11.19.0.7 reset_cycle(name = "default")
Resets a cycle (see the cycle method in this section) so that it starts cycling from its first element the next time it is called. Pass in a name to reset a named cycle.
11.19.0.8 simple_format(text, html_options = {}, options = {})
Returns text transformed into HTML using simple formatting rules. Two or more consecutive newlines (\n\n) are considered to denote a paragraph and thus are wrapped in p tags. One newline (\n) is considered to be a line break and a br tag is appended. This method does not remove the newlines from the text.
Any attributes set in html_options will be added to all outputted paragraphs. The following options are also available:
:sanitize
Setting this option to false will not sanitize any text.
:wrapper_tag
A string representing the wrapper tag, defaults to "p".
11.19.0.9 truncate(text, options = {}, &block)
If text is longer than the :length option (defaults to 30), text will be truncated to the length specified and the last three characters will be replaced with the the :omission (defaults to "..."). The :separator option allows defining the delimitation. Finally, to not escape the output, set :escapeto false.
1 truncate("Once upon a time in a world far far away", length: 7)
2 => "Once..."
3
4 truncate("Once upon a time in a world far far away")
5 # => "Once upon a time in a world..."
6
7 truncate("And they found that many people were sleeping better.",
8 length: 25, omission: '... (continued)')
9 # => "And they f... (continued)"
11.19.0.10 word_wrap(text, options = {})
Wraps the text into lines no longer than the :line_width option. This method breaks on the first whitespace character that does not exceed :line_width (which is 80 by default).
1 word_wrap('Once upon a time')
2 # => Once upon a time
3
4 word_wrap('Once upon a time', line_width: 8)
5 # => Once\nupon a\ntime
6
7 word_wrap('Once upon a time', line_width: 1)
8 # => Once\nupon\na\ntime
11.20 TranslationHelper and the I18n API
I18n stands for internationalization and the I18n gem that ships with Rails makes it easy to support multiple languages other than English in your Rails applications. When you internationalize your app, you do a sweep of all the textual content in your models and views that needs to be translated, as well as demarking data like currency and dates, which should be subject to localization.46
using I18n in Rails, by Sven Fuchs and Karel Minarik, available at http://guides.rubyonrails.org/i18n.html.
Rails provides an easy-to-use and extensible framework for translating your application to a single custom language other than English or for providing multi-language support in your application.
The process of internationalization in Rails involves the abstraction of strings and other locale-specific parts of your application (such as dates and currency formats) out of the codebase and into a locale file.
The process of localization means to provide translations and localized formats for the abstractions created during internationalization. In the process of localizing your application you’ll probably want to do following three things:
· Replace or add to Rails’ default locale.
· Abstract strings used in your application into keyed dictionaries—e.g. flash messages, static text in your views, etc.
· Store the resulting dictionaries somewhere.
Internationalization is a complex problem. Natural languages differ in so many ways (e.g. in pluralization rules) that it is hard to provide tools for solving all problems at once. For that reason the Rails I18n API focuses on:
· Providing support for English and similar languages by default.
· Making it easy to customize and extend everything for other languages.
As part of this solution, every static string in the Rails framework—e.g. Active Record validation messages, time and date formats—has been internationalized, so localization of a Rails application means overriding Rails defaults.
11.20.1 Localized Views
Before diving into the more complicated localization techniques, lets briefly cover a simple way to translate views that is useful for content-heavy pages. Assume you have a BooksController in your application. Your index action renders content in app/views/books/index.html.haml template. When you put a localized variant of that template such as index.es.html.haml in the same directory, Rails will recognize it as the appropriate template to use when the locale is set to :es. If the locale is set to the default, the generic index.html.haml view will be used normally.
You can make use of this feature when working with a large amount of static content that would be clumsy to maintain inside locale dictionaries. Just bear in mind that any changes to a template must be kept in sync with all of its translations.
11.20.2 TranslationHelper Methods
The following two methods are provided for use in your views and assume that I18n support is setup in your application.
11.20.2.1 localize(*args) aliased to l
Delegates to ActiveSupport’s I18n#translate method with no additional functionality. Normally you want to use translate instead.
11.20.2.2 translate(key, options = {}) aliased to t
Delegates to ActiveSupport’s I18n#translate method, while performing three additional functions. First, it’ll catch MissingTranslationData exceptions and turn them into inline spans that contain the missing key, such that you can see within your views when keys are missing.
Second, it’ll automatically scope the key provided by the current partial if the key starts with a period. So if you call translate(".foo") from the people/index.html.haml template, you’ll be calling I18n.translate("people.index.foo"). This makes it less repetitive to translate many keys within the same partials and gives you a simple framework for scoping them consistently. If you don’t prepend the key with a period, nothing is converted.
Third, it’ll mark the translation as safe HTML if the key has the suffix “_html” or the last element of the key is the word “html”. For example, calling translate(“header.html”) will return a safe HTML string which won’t be escaped.
11.20.3 I18n Setup
There are just a few simple steps to get up and running with I18n support for your application.
Following the convention over configuration philosophy, Rails will set up your application with reasonable defaults. If you need different settings, you can overwrite them easily.
Rails adds all .rb and .yml files from the config/locales directory to your translations load path, automatically.47 The default en.yml locale in this directory contains a sample pair of translation strings:
1 en:
2 hello: "Hello world"
This means, that in the :en locale, the key hello will map to the “Hello world” string.48
You can use YAML or standard Ruby hashes to store translations in the default (Simple) backend.
Unless you change it, the I18n library will use English (:en) as its default locale for looking up translations. Change the default in using code similar to:
config.i18n.default_locale = :de
Note
The i18n library takes a pragmatic approach to locale keys (after some discussion49), including only the locale (“language”) part, like :en, :pl, not the region part, like :en-US or :en-UK, which are traditionally used for separating “languages” and “regional setting” or “dialects”. Many international applications use only the “language” element of a locale such as :cz, :th or :es (for Czech, Thai and Spanish). However, there are also regional differences within different language groups that may be important. For instance, in the :en-US locale you would have $ as a currency symbol, while in :en-UK, you would have . Nothing stops you from separating regional and other settings in this way: you just have to provide full “English – United Kingdom” locale in a :en-UKdictionary. Rails I18n plugins such as Globalize350 may help you implement it.
11.20.4 Setting and Passing the Locale
If you want to translate your Rails application to a single language other than English, you can just set default_locale to your locale in application.rb as shown above and it will persist through the requests. However, you probably want to provide support for more locales in your application, depending on the user’s preference. In such case, you need to set and pass the locale between requests.
Warning You may be tempted to store the chosen locale in a session or a cookie. Do not do so. The locale should be transparent and a part of the URL. This way you don’t break people’s basic assumptions about the web itself: if you send a URL of some page to a friend, she should see the same page, same content. |
You can set the locale in a before_action in your ApplicationController like:
1 before_action :set_locale
2
3 def set_locale
4 # if params[:locale] is nil then I18n.default_locale will be used
5 I18n.locale = params[:locale]
6 end
This approach requires you to pass the locale as a URL query parameter as in http://example.com/books?locale=pt. (This is, for example, Google’s approach.)
Getting the locale from params and setting it accordingly is not the hard part of this technique. Including the locale parameter in every URL generated by your application is the hard part. To include an explicit option in every URL
= link_to books_url(locale: I18n.locale)
would be tedious at best and impossible to maintain at worst.
A default_url_options method in ApplicationController is useful precisely in this scenario. It enables us to set defaults for url_for and helper methods dependent on it.
1 def default_url_options(options={})
2 logger.debug "default_url_options is passed options: #{options.inspect}\n"
3 { locale: I18n.locale }
4 end
Every helper method dependent on url_for (e.g. helpers for named routes like root_path or root_url, resource routes like books_path or books_url, etc.) will now automatically include the locale in the query string, like
http://localhost:3000/?locale=ja
Having the locale hang at the end of every path in your application can negatively impact readability of your URLs. Moreover, from an architectural standpoint, locales are a concept that live above other parts of your application domain and your URLs should probably reflect that.
You might want your URLs to look more like www.example.com/en/books (which loads the English locale) and www.example.com/nl/books (which loads the Netherlands locale). This is achievable with the same default_url_options strategy we just reviewed. You just have to set up your routes with a scope option in this way:
1 # config/routes.rb
2 scope "/:locale" do
3 resources :books
4 end
Even with this approach, you still need to take special care of the root URL of your application. An URL like http://localhost:3000/nl will not work automatically, because the root "books#index" declaration in your routes.rb doesn’t take locale into account. After all, there should only be one “root” of your website.
A possible solution is to map a URL like:
# config/routes.rb
get '/:locale' => "dashboard#index"
Do take special care about the order of your routes, so this route declaration does not break other ones. It would be most wise to add it directly before the root declaration at the end of your routes file.
Warning This solution has currently one rather big downside. Due to the default_url_options implementation, you have to pass the :id option explicitly, like link_to 'Show', book_url(id: book) and not depend on Rails’ magic in code like link_to 'Show', book. If this should be a problem, have a look at Sven Fuchs’s routing_filter51 plugin which simplify work with routes in this way. |
11.20.4.1 Setting the Locale from the Domain Name
Another option you have is to set the locale from the domain name where your application runs. For example, we want www.example.com to load the English (or default) locale, and www.example.es to load the Spanish locale. Thus the top-level domain name is used for locale setting. This has several advantages:
· The locale is a very obvious part of the URL.
· People intuitively grasp in which language the content will be displayed.
· It is very trivial to implement in Rails.
· Search engines seem to like that content in different languages lives at different, inter-linked domains
You can implement it like this in your ApplicationController:
1 before_action :set_locale
2
3 def set_locale
4 I18n.locale = extract_locale_from_uri
5 end
6
7 # Get locale from top-level domain or return nil
8 def extract_locale_from_tld
9 parsed_locale = request.host.split('.').last
10 (available_locales.include? parsed_locale) ? parsed_locale : nil
11 end
Try adding localhost aliases to your file to test this technique.
127.0.0.1 application.com
127.0.0.1 application.it
127.0.0.1 application.pl
11.20.4.2 Setting the Locale from the Host Name
We can also set the locale from the subdomain in a very similar way inside of ApplicationController.
1 before_action :set_locale
2
3 def set_locale
4 I18n.locale = extract_locale_from_uri
5 end
6
7 def extract_locale_from_subdomain
8 parsed_locale = request.subdomains.first
9 (available_locales.include? parsed_locale) ? parsed_locale : nil
10 end
11.20.5 Setting Locale from Client Supplied Information
In specific cases, it would make sense to set the locale from client-supplied information, i.e. not from the URL. This information may come for example from the users’ preferred language (set in their browser), can be based on the users’ geographical location inferred from their IP, or users can provide it simply by choosing the locale in your application interface and saving it to their profile. This approach is more suitable for web-based applications or services, not for websites. See the sidebar about sessions, cookies and RESTful architecture.
11.20.5.1 Using Accept-Language
One source of client supplied information would be an Accept-Language HTTP header. People may set this in their browser52 or other clients (such as curl).
A trivial implementation of setting locale based on the Accept-Language header in ApplicationController might be:
1 before_action :set_locale
2
3 def set_locale
4 I18n.locale = extract_locale_from_accept_language_header
5 logger.debug "* Locale set to '#{I18n.locale}'"
6 end
7
8 private
9
10 def extract_locale_from_accept_language_header
11 request.env['HTTP_ACCEPT_LANGUAGE'].scan(/^[a-z]{2}/).first
12 end
In real production environments you should use much more robust code that the example above. Try plugins such as Iain Hecker’s http_accept_language53 or even Rack middleware such as locale54.
11.20.5.2 Using GeoIP (or Similar) Database
Yet another way of choosing the locale from client information would be to use a database for mapping the client IP to the region, such as GeoIP Lite Country55. The mechanics of the code would be very similar to the code above—you would need to query the database for the user’s IP, and look up your preferred locale for the country/region/city returned.
11.20.5.3 User Profile
You can also provide users of your application with means to set (and possibly override) the locale in your application interface, as well. Again, mechanics for this approach would be very similar to the code above—you’d probably let users choose a locale from a dropdown list and save it to their profile in the database. Then you’d set the locale to this value using a before_action in ApplicationController.
11.20.6 Internationalizing Your Application
After you’ve setup I18n support for your Ruby on Rails application and told it which locale to use and how to preserve it between requests, you’re ready for the really interesting part of the process: actually internationalizing your application.
11.20.6.1 The Public I18n API
First of all, you should be acquainted with the I18n API. The two most important methods of the I18n API are
translate # Lookup text translations
localize # Localize Date and Time objects to local formats
These have the aliases #t and #l so you can use them like
I18n.t 'store.title'
I18n.l Time.now
11.20.6.2 The Process
Take the following basic pieces of a simple Rails application as an example for describing the process.
1 # config/routes.rb
2 Rails.application.routes.draw do
3 root "home#index"
4 end
5
6 # app/controllers/home_controller.rb
7 classHomeController < ApplicationController
8 def index
9 flash[:notice] = "Welcome"
10 end
11 end
12
13 # app/views/home/index.html.haml
14 %h1 Hello world!
15 %p.notice= flash[:notice]
The example has two strings that are currently hardcoded in English. To internationalize this code, we must replace those strings with calls to Rails’ #t helper with a key that makes sense for the translation.
1 # app/controllers/home_controller.rb
2 classHomeController < ApplicationController
3 def index
4 flash[:notice] = t(:welcome_flash)
5 end
6 end
7
8 # app/views/home/index.html.haml
9 %h1= t(:hello_world)
10 %p.notice= flash[:notice]
Now when you render this view, it will show an error message which tells you that the translations for the keys :hello_world and :welcome_flash are missing.
Rails adds a t (translate) helper method to your views so that you do not need to spell out I18n.t all the time. Additionally this helper will catch missing translations and wrap the resulting error message into a <span class="translation_missing">.
To make the example work you would add the missing translations into the dictionary files (thereby doing the localization part of the work):
1 # config/locale/en.yml
2 en:
3 hello_world: Hello World
4 welcome_flash: Welcome
5
6 # config/locale/pirate.yml
7 pirate:
8 hello_world: Ahoy World
9 welcome_flash: All aboard!
Note
You need to restart the server when you add or edit locale files.
You may use YAML (.yml) or plain Ruby (.rb) files for storing your translations. YAML is the preferred option among Rails developers. However, it has one big disadvantage. YAML is very sensitive to whitespace and special characters, so the application may not load your dictionary properly. Ruby files will crash your application on first request, so you may easily find what’s wrong. (If you encounter any “weird issues” with YAML dictionaries, try putting the relevant portion of your dictionary into a Ruby file.)
11.20.6.3 Adding Date/Time Formats
Okay! Now let’s add a timestamp to the view, so we can demo the date/time localization feature as well. To localize the time format you pass the Time object to I18n.l or use Rails’ #l helper method in your views.
1 # app/views/home/index.html.haml
2 %h1= t(:hello_world)
3 %p.notice= flash[:notice]
4 %p= l(Time.now, format: :short)
And in our pirate translations file let’s add a time format (it’s already there in Rails’ defaults for English):
1 # config/locale/pirate.yml
2 pirate:
3 time:
4 formats:
5 short: "arrrround %H'ish"
The rails-i18n repository
There’s a great chance that somebody has already done much of the hard work of translating Rails’ defaults for your locale. See the rails-i18n repository at GitHub56 for an archive of various locale files. When you put such file(s) in config/locale/ directory, they will automatically be ready for use.
11.20.7 Organization of Locale Files
Putting translations for all parts of your application in one file per locale could be hard to manage. You can store these files in a hierarchy which makes sense to you.
For example, your config/locale directory could look like:
|-defaults
|---es.rb
|---en.rb
|-models
|---book
|-----es.rb
|-----en.rb
|-views
|---defaults
|-----es.rb
|-----en.rb
|---books
|-----es.rb
|-----en.rb
|---users
|-----es.rb
|-----en.rb
|---navigation
|-----es.rb
|-----en.rb
This way, you can separate model and model attribute names from text inside views, and all of this from the “defaults” (e.g. date and time formats). Other stores for the i18n library could provide different means of such separation.
Note
The default locale loading mechanism in Rails does not load locale files in nested dictionaries, like we have here. So, for this to work, we must explicitly tell Rails to look further through settings in :
1 # config/application.rb
2 config.i18n.load_path += Dir[File.join(Rails.root, 'config',
3 'locales', '**', '*.{rb,yml}')]
11.20.8 Looking up Translations
11.20.8.1 Basic Lookup, Scopes and Nested Keys
Translations are looked up by keys which can be both Symbols or Strings, so these calls are equivalent:
I18n.t :message
I18n.t 'message'
The translate method also takes a :scope option which can contain one or more additional keys that will be used to specify a “namespace” or scope for a translation key:
I18n.t :invalid, scope: [:activerecord, :errors, :messages]
This looks up the :invalid message in the Active Record error messages.
Additionally, both the key and scopes can be specified as dot-separated keys as in:
I18n.translate :"activerecord.errors.messages.invalid"
Thus the following four calls are equivalent:
I18n.t 'activerecord.errors.messages.invalid'
I18n.t 'errors.messages.invalid', scope: :activerecord
I18n.t :invalid, scope: 'activerecord.errors.messages'
I18n.t :invalid, scope: [:activerecord, :errors, :messages]
11.20.8.2 Default Values
When a :default option is given, its value will be returned if the translation is missing:
I18n.t :missing, default: 'Not here'
# => 'Not here'
If the :default value is a Symbol, it will be used as a key and translated. One can provide multiple values as default. The first one that results in a value will be returned.
E.g., the following first tries to translate the key :missing and then the key :also_missing. As both do not yield a result, the string “Not here” will be returned:
I18n.t :missing, default: [:also_missing, 'Not here']
# => 'Not here'
11.20.8.3 Bulk and Namespace Lookup
To look up multiple translations at once, an array of keys can be passed:
I18n.t [:odd, :even], scope: 'activerecord.errors.messages'
# => ["must be odd", "must be even"]
Also, a key can translate to a (potentially nested) hash of grouped translations. For instance, one can receive all Active Record error messages as a Hash with:
I18n.t 'activerecord.errors.messages'
# => { inclusion: "is not included in the list", exclusion: ... }
11.20.8.4 View Scoped Keys
Rails implements a convenient way to reference keys inside of views. Assume you have the following local file:
1 es:
2 books:
3 index:
4 title: "Título"
You can reference the value of books.index.title inside of the app/views/books/index.html.haml template by prefixing the key name with a dot. Rails will automatically fill in the scope based on the identity of the view.
= t '.title'
11.20.8.5 Interpolation
In many cases you want to abstract your translations in such a way that variables can be interpolated into the translation. For this reason the I18n API provides an interpolation feature.
All options besides :default and :scope that are passed to translate will be interpolated to the translation:
I18n.backend.store_translations :en, thanks: 'Thanks %{name}!
I18n.translate :thanks, name: 'Jeremy'
# => 'Thanks Jeremy!'
If a translation uses :default or :scope as an interpolation variable, an I18n::ReservedInterpolationKey exception is raised. If a translation expects an interpolation variable, but this has not been passed to translate, an I18n::MissingInterpolationArgument exception is raised.
11.20.8.6 Pluralization
In English there are only one singular and one plural form for a given string, e.g. “1 message” and “2 messages” but other languages have different grammars with additional or fewer plural forms57. Thus, the I18n API provides a flexible pluralization feature.
The :count interpolation variable has a special role in that it both is interpolated to the translation and used to pick a pluralization from the translations according to the pluralization rules defined by Unicode:
1 I18n.backend.store_translations :en, inbox: {
2 one: '1 message',
3 other: '%{count} messages'
4 }
5
6 I18n.translate :inbox, count: 2
7 # => '2 messages'
8
9 I18n.translate :inbox, count: 1
10 # => 'one message'
The algorithm for pluralizations in :en is as simple as:
1 entry[count == 1 ? 0 : 1]
The translation denoted as :one is regarded as singular, versus any other value regarded as plural (including the count being zero).
If the lookup for the key does not return a Hash suitable for pluralization, an I18n::InvalidPluralizationData exception is raised.
11.20.9 How to Store Your Custom Translations
The Simple backend shipped with Active Support allows you to store translations in both plain Ruby and YAML format. A Ruby hash locale file would look like:
1 {
2 pt: {
3 foo: {
4 bar: "baz"
5 }
6 }
7 }
The equivalent YAML file would look like:
1 pt:
2 foo:
3 bar: baz
In both cases the top level key is the locale. :foo is a namespace key and :bar is the key for the translation “baz”.
Here is a real example from the Active Support en.yml translations YAML file:
1 en:
2 date:
3 formats:
4 default: "%Y-%m-%d"
5 short: "%b %d"
6 long: "%B %d, %Y"
So, all of the following equivalent lookups will return the :short date format "%B %d":
1 I18n.t 'date.formats.short'
2 I18n.t 'formats.short', scope: :date
3 I18n.t :short, scope: 'date.formats'
4 I18n.t :short, scope: [:date, :formats]
Generally we recommend using YAML as a format for storing translations.
11.20.9.1 Translations for Active Record Models
You can use the methods Model.human_name and Model.human_attribute_name(attribute) to transparently look up translations for your model and attribute names.
For example when you add the following translations:
1 en:
2 activerecord:
3 models:
4 user: Dude
5 attributes:
6 user:
7 login: "Handle"
8 # will translate User attribute "login" as "Handle"
User.human_name will return “Dude” and User.human_attribute_name(:login) will return “Handle”.
11.20.9.2 Error Message Scopes
Active Record validation error messages can also be translated easily. Active Record gives you a couple of namespaces where you can place your message translations in order to provide different messages and translation for certain models, attributes, and/or validations. It also transparently takes single table inheritance into account.
This gives you quite powerful means to flexibly adjust your messages to your application’s needs.
Consider a User model with a validates_presence_of validation for the name attribute like:
1 classUser < ActiveRecord::Base
2 validates_presence_of :name
3 end
The key for the error message in this case is :blank. Active Record will look up this key in the namespaces:
1 activerecord.errors.models.[model_name].attributes.[attribute_name]
2 activerecord.errors.models.[model_name]
3 activerecord.errors.messages
Thus, in our example it will try the following keys in this order and return the first result:
1 activerecord.errors.models.user.attributes.name.blank
2 activerecord.errors.models.user.blank
3 activerecord.errors.messages.blank
When your models are additionally using inheritance then the messages are looked up in the inheritance chain.
For example, you might have an Admin model inheriting from User:
1 classAdmin < User
2 validates_presence_of :name
3 end
Then Active Record will look for messages in this order:
1 activerecord.errors.models.admin.attributes.title.blank
2 activerecord.errors.models.admin.blank
3 activerecord.errors.models.user.attributes.title.blank
4 activerecord.errors.models.user.blank
5 activerecord.errors.messages.blank
This way you can provide special translations for various error messages at different points in your models inheritance chain and in the attributes, models, or default scopes.
11.20.9.3 Error Message Interpolation
The translated model name, translated attribute name, and value are always available for interpolation.
So, for example, instead of the default error message "can not be blank" you could use the attribute name like "Please fill in your %{attribute}".
Validation interpolation |
with option |
Message |
Interpolation |
validates_confirmation_of |
- |
:confirmation |
- |
validates_acceptance_of |
- |
:accepted |
- |
validates_presence_of |
- |
:blank |
- |
validates_length_of |
:within, :in |
:too_short |
count |
validates_length_of |
:within, :in |
:too_long |
count |
validates_length_of |
:is |
:wrong_length |
count |
validates_length_of |
:minimum |
:too_short |
count |
validates_length_of |
:maximum |
:too_long |
count |
validates_format_of |
- |
:taken |
- |
validates_uniqueness_of |
- |
:invalid |
- |
validates_inclusion_of |
- |
:inclusion |
- |
validates_exclusion_of |
- |
:exclusion |
- |
validates_associated |
- |
:invalid |
- |
validates_numericality_of |
- |
:not_a_number |
- |
validates_numericality_of |
:greater_than |
:greater_than |
count |
validates_numericality_of |
:greater_than_or_equal_to |
:greater_than_or_equal_to |
count |
validates_numericality_of |
:equal_to |
:equal_to |
count |
validates_numericality_of |
:less_than_or_equal_to |
::less_than_or_equal_to |
count |
validates_numericality_of |
:odd |
:odd |
- |
validates_numericality_of |
:even |
:even |
- |
11.20.10 Overview of Other Built-In Methods that Provide I18n Support
Rails uses fixed strings and other localizations, such as format strings and other format information in a couple of helpers. Here’s a brief overview.
11.20.10.1 Action View Helper Methods
· distance_of_time_in_words translates and pluralizes its result and interpolates the number of seconds, minutes, hours, and so on. See datetime.distance_in_words58 translations.
· datetime_select and select_month use translated month names for populating the resulting select tag. See date.month_names59 for translations. datetime_select also looks up the order option from date.order60 (unless you pass the option explicitely). All date selection helpers translate the prompt using the translations in the datetime.prompts61 scope if applicable. *The number_to_currency, number_with_precision, number_to_percentage, number_with_delimiter, and number_to_human_size helpers use the number format settings located in the number62 scope.
11.20.10.2 Active Record Methods
· human_name and human_attribute_name use translations for model names and attribute names if available in the activerecord.models63 scope. They also support translations for inherited class names (e.g. for use with STI) as explained in “Error message scopes”.
· ActiveRecord::Errors#generate_message (which is used by Active Record validations but may also be used manually) uses human_name and human_attribute_name. It also translates the error message and supports translations for inherited class names as explained in “Error message scopes”.
· ActiveRecord::Errors#full_messages prepends the attribute name to the error message using a separator that will be looked up from activerecord.errors.format (and which defaults to "%{attribute} %{message}").
11.20.10.3 Active Support Methods
· Array#to_sentence uses format settings as given in the support.array scope.
11.20.11 Exception Handling
In some contexts you might want to I18n’s default exception handling behavior. For instance, the default exception handling does not allow to catch missing translations during automated tests easily. For this purpose a different exception handler can be specified. The specified exception handler must be a method on the I18n module. You would add code similar to the following to your file or other kind of initializer.
1 moduleI18n
2 def just_raise_that_exception(*args)
3 raise args.first
4 end
5 end
6
7 I18n.exception_handler = :just_raise_that_exception
This would re-raise all caught exceptions including MissingTranslationData.
11.21 UrlHelper
This module provides a set of methods for making links and getting URLs that depend on the routing subsystem, covered extensively in Chapter 2, “Routing” and Chapter 3, “REST, Resources, and Rails” of this book.
11.21.0.1 button_to(name = nil, options = nil, html_options = nil, &block)
Generates a form containing a single button that submits to the URL created by the set of options. This is the safest method to ensure that links that cause changes to your data are not triggered by search bots or accelerators. If the HTML button does not work with your layout, you can also consider using the link_to method (also in this module) with the :method modifier.
The options hash accepts the same options as the url_for method.
The generated form element has a class name of button-to to allow styling of the form itself and its children. This class name can be overridden by setting :form_class in :html_options. The :method option work just like the link_to helper. If no :method modifier is given, it defaults to performing a POST operation.
1 button_to("New", action: "new")
2 # => "<form method="post" action="/controller/new" class="button-to">
3 # <div><input value="New" type="submit" /></div>
4 # </form>"
5
6 button_to "Delete Image", { action: "delete", id: @image.id },
7 method: :delete, data: { confirm: "Are you sure?" }
8 # => "<form method="post" action="/images/delete/1" class="button_to">
9 # <div>
10 # <input type="hidden" name="_method" value="delete" />
11 # <input data-confirm='Are you sure?'
12 # value="Delete Image" type="submit" />
13 # <input name="authenticity_token" type="hidden"
14 # value="10f2163b45388899..."/>
15 # </div>
16 # </form>"
11.21.0.2 current_page?(options)
Returns true if the current request URI was generated by the given options. For example, let’s assume that we’re currently rendering the /shop/checkout action:
1 current_page?(action: 'process')
2 # => false
3
4 current_page?(action: 'checkout') # controller is implied
5 # => true
6
7 current_page?(controller: 'shop', action: 'checkout')
8 # => true
11.21.0.3 link_to(name = nil, options = nil, html_options = nil, &block)
One of the fundamental helper methods. Creates a link tag of the given name using a URL created by the set of options. The valid options are covered in the description of this module’s url_for method. It’s also possible to pass a string instead of an options hash to get a link tag that uses the value of the string as the href for the link. If nil is passed as a name, the link itself will become the name.
:data
Adds custom data attributes.
method: symbol
Specify an alternative HTTP verb for this request (other than GET). This modifier will dynamically create an HTML form and immediately submit the form for processing using the HTTP verb specified (:post, :patch, or :delete).
remote: true
Allows the unobtrusive JavaScript driver to make an Ajax request to the URL instead of the following the link.
The following data attributes work alongside the unobtrusive JavaScript driver:
confirm: 'question?'
The unobtrusive JavaScript driver will display a JavaScript confirmation prompt with the question specified. If the user accepts, the link is processed normally; otherwise, no action is taken.
:disable_with
Used by the unobtrusive JavaScript driver to provide a name for disabled versions.
Generally speaking, GET requests should be idempotent, that is, they do not modify the state of any resource on the server, and can be called one or many times without a problem. Requests that modify server-side resources or trigger dangerous actions like deleting a record should not usually be linked with a normal hyperlink, since search bots and so-called browser accelerators can follow those links while spidering your site, leaving a trail of chaos.
If the user has JavaScript disabled, the request will always fall back to using GET, no matter what :method you have specified. This is accomplished by including a valid href attribute. If you are relying on the POST behavior, your controller code should check for it using the post?, delete?, or patch? methods of request.
As usual, the html_options will accept a hash of HTML attributes for the link tag.
1 = link_to "Help", help_widgets_path
2
3 = link_to "Rails", "http://rubyonrails.org/",
4 data: { confirm: "Are you sure?" }
5
6 = link_to "Delete", widget_path(@widget), method: :delete,
7 data: { confirm: "Are you sure?" }
8
9 [Renders in the browser as...]
10
11 <a href="/widgets/help">Help</a>
12
13 <a href="http://rubyonrails.org/" data-confirm="Are you sure?">Rails</a>
14
15 <a href="/widgets/42" rel="nofollow" data-method="delete"
16 data-confirm="Are you sure?">View</a>
11.21.0.4 link_to_if(condition, name, options = {}, html_options = {}, &block)
Creates a link tag using the same options as link_to if the condition is true; otherwise, only the name is output (or block is evaluated for an alternative value, if one is supplied).
11.21.0.5 link_to_unless(condition, name, options = {}, html_options = {}, &block)
Creates a link tag using the same options as link_to unless the condition is true, in which case only the name is output (or block is evaluated for an alternative value, if one is supplied).
11.21.0.6 link_to_unless_current(name, options = {}, html_options = {}, &block)
Creates a link tag using the same options as link_to unless the condition is true, in which case only the name is output (or block is evaluated for an alternative value, if one is supplied).
This method is pretty useful sometimes. Remember that the block given to link_to_unless_current is evaluated if the current action is the action given. So, if we had a comments page and wanted to render a “Go Back” link instead of a link to the comments page, we could do something like
1 link_to_unless_current("Comment", { controller: 'comments', action: 'new}) do
2 link_to("Go back", posts_path)
3 end
11.21.0.7 mail_to(email_address, name = nil, html_options = {}, &block)
Creates a mailto link tag to the specified email_address, which is also used as the name of the link unless name is specified. Additional HTML attributes for the link can be passed in html_options.
The mail_to helper has several methods for customizing the email address itself by passing special keys to html_options:
:subject
The subject line of the email.
:body
The body of the email.
:cc
Add cc recipients to the email.
:bcc
Add bcc recipients to the email.
Here are some examples of usages:
1 mail_to "me@domain.com"
2 # => <a href="mailto:me@domain.com">me@domain.com</a>
3
4 mail_to "me@domain.com", "My email"
5 # => <a href="mailto:me@domain.com">My email</a>
6
7 mail_to "me@domain.com", "My email", cc: "ccaddress@domain.com",
8 subject: "This is an email"
9 # => <a href="mailto:me@domain.com?cc=ccaddress@domain.com&
10 subject=This%20is%20an%20email">My email</a>
Note
In previous versions of Rails, the mail_to helper provided options for encoding the email address to hinder email harvesters. If your application is still dependent on these options, add the actionview-encoded_mail_to gem to your Gemfile
11.21.0.8 Redirecting Back
If you pass the magic symbol :back to any method that uses url_for under the covers (redirect_to, etc.) the contents of the HTTP_REFERER request header will be returned. (If a referer is not set for the current request, it will return javascript:history.back() to try to make the browser go back one page.)
url_for(:back)
# => "javascript:history.back()"
11.22 Writing Your Own View Helpers
As you develop an application in Rails, you should be on the lookout for opportunities to refactor duplicated view code into your own helper methods. As you think of these helpers, you add them to one of the helper modules defined in the app/helpers folder of your application.
There is an art to effectively writing helper methods, similar in nature to what it takes to write effective APIs. Helper methods are basically a custom, application-level API for your view code. It is difficult to teach API design in a book form. It’s the sort of knowledge that you gain by apprenticing with more experienced programmers and lots of trial and error. Nevertheless, in this section, we’ll review some varied use cases and implementation styles that we hope will inspire you in your own application design.
11.22.1 Small Optimizations: The Title Helper
Here is a simple helper method that has been of use to me on many projects now. It’s called page_title and it combines two simple functions essential to a good HTML document:
· Setting the title of the page in the document’s head.
· Setting the content of the page’s h1 element.
This helper assumes that you want the title and h1 elements of the page to be the same, and has a dependency on your application template. The code for the helper is in Listing 11.3 and would be added to app/helpers/application_helper.rb, since it is applicable to all views.
Listing 11.3: The page_title Helper
1 def page_title(name)
2 content_for(:title) { name }
3 content_tag("h1", name)
4 end
First it sets content to be yielded in the layout as :title and then it outputs an h1 element containing the same text. I could have used string interpolation on the second line, such as "<h1>#{name}</h1>", but it would have been sloppier than using the built-in Rails helper method content_tag.
My application template is now written to yield :title so that it gets the page title.
1 %html
2 %head
3 %title= yield :title
As should be obvious, you call the page_title method in your view template where you want to have an h1 element:
1 - page_title "New User"
2 = form_for(user) do |f|
3 ...
11.22.2 Encapsulating View Logic: The photo_for Helper
Here’s another relatively simple helper. This time, instead of simply outputting data, we are encapsulating some view logic that decides whether to display a user’s profile photo or a placeholder image. It’s logic that you would otherwise have to repeat over and over again throughout your application.
The dependency (or contract) for this particular helper is that the user object being passed in has a profile_photo associated to it, which is an attachment model based on Rick Olson’s old attachment_fu Rails plugin. The code in Listing 11.4 should be easy enough to understand without delving into the details of attachment_fu. Since this is an example, I broke out the logic for setting src into an if/else structure; otherwise, this would be a perfect place to use Ruby’s ternary operator.
Listing 11.4: The photo—for helper encapsulating common view logic
1 def photo_for(user, size=:thumb)
2 if user.profile_photo
3 src = user.profile_photo.public_filename(size)
4 else
5 src = 'user_placeholder.png'
6 end
7 link_to(image_tag(src), user_path(user))
8 end
Tim says…
Luckily, the latest generation of attachment plugins such as Paperclip and CarrierWave use a NullObject pattern to alleviate the need for you to do this sort of thing.
11.22.3 Smart View: The breadcrumbs Helper
Lots of web applications feature user-interface concepts called breadcrumbs. They are made by creating a list of links, positioned near the top of the page, displaying how far the user has navigated into a hierarchically organized application. I think it makes sense to extract breadcrumb logic into its own helper method instead of leaving it in a layout template.
The trick to our example implementation (shown in Listing 11.5) is to use the presence of helper methods exposed by the controller, on a convention specific to your application, to determine whether to add elements to an array of breadcrumb links.
Listing 11.5: breadcrumbs Helper Method for a Corporate Directory Application
1 def breadcrumbs
2 returnif controller.controller_name == 'home'
3
4 html = [link_to('Home', root_path)]
5
6 # first level
7 html << link_to(company.name, company) if respond_to? :company
8
9 # second level
10 html << link_to(department.name, department) if respond_to? :department
11
12 # third and final level
13 html << link_to(employee.name, employee) if respond_to? :employee
14
15 html.join(' > ').html_safe
16 end
Here’s the line-by-line explanation of the code, noting where certain application-design assumptions are made:
On line 2, we abort execution if we’re in the context of the application’s homepage controller, since its pages don’t ever need breadcrumbs. A simple return with no value implicitly returns nil, which is fine for our purposes. Nothing will be output to the layout template.
On line 4 we are starting to build an array of HTML links, held in the html local variable, which will ultimately hold the contents of our breadcrumb trail. The first link of the breadcrumb trail always points to the home page of the application, which of course will vary, but since it’s always there we use it to initialize the array. In this example, it uses a named route called root_path.
After the html array is initialized, all we have to do is check for the presence of the methods returning objects that make up the hierarchy (lines 7 to 13). It is assumed that if a department is being displayed, its parent company will also be in scope. If an employee is being displayed, both department and company will be in scope as well. This is not just an arbitrary design choice. It is a common pattern in Rails applications that are modelled on REST principles and using nested resource routes.
Finally, on line 15, the array of HTML links is joined with the > character, to give the entire string the traditional breadcrumb appearance. The call to html_safe tells the rendering system that this is HTML code and we’re cool with that—don’t sanitize it!
11.23 Wrapping and Generalizing Partials
I don’t think that partials (by themselves) lead to particularly elegant or concise template code. Whenever there’s a shared partial template that gets used over and over again in my application, I will take the time to wrap it up in a custom helper method that conveys its purpose and formalizes its parameters. If appropriate, I might even generalize its implementation to make it more of a lightweight, reusable component. (Gasp!)
11.23.1 A tiles Helper
Let’s trace the steps to writing a helper method that wraps what I consider to be a general-purpose partial. Listing 11.6 contains code for a partial for a piece of a user interface that is common to many applications, and generally referred to as a tile. It pairs a small thumbnail photo of something on the left side of the widget with a linked name and description on the right.
Tiles can also represent other models in your application, such as users and files. As I mentioned, tiles are a very common construct in modern user interfaces and operating systems. So let’s take the cities tiles partial and transform it into something that can be used to display other types of data.
Note
I realize that it has become passé to use HTML tables and I happen to agree that div-based layouts plus CSS are a lot more fun and flexible to work with. However, for the sake of simplicity in this example, and since the UI structure we’re describing is tabular, I’ve decided to structure it using a table.
Listing 11.6: A tiles partial prior to wrapping and generalization
1 %table.cities.tiles
2 - cities.in_groups_of(columns) do |row|
3 %tr
4 - row.each do |city|
5 %td[city]
6 .left
7 = image_tag(city.photo.url(:thumb))
8 .right
9 .title
10 = city.name
11 .description
12 = city.description
11.23.1.1 Explanation of the Tiles Partial Code
Since we’re going to transform this city-specific partial into a generalized UI component, I want to make sure that the code we start with makes absolute sense to you first. Before proceeding, I’m going through the implementation line by line and explaining what everything in Listing 11.6does.
Line 1 opens up the partial with a table element and gives it semantically significant CSS classes so that the table and its contents can be properly styled.
Line 2 leverages a useful Array extension method provided by ActiveSupport, called in_groups_of. It uses both of the local variables: cities and columns. Both will need to be passed into this partial using the :locals option of the render :partial method. The cities variable will hold the list of cities to be displayed, and columns is an integer representing how many city tiles each row should contain. A loop iterates over the number of rows that will be displayed in this table.
Line 3 begins a table row using the tr element.
Line 4 begins a loop over the tiles for each row to be displayed, yielding a city for each.
Line 5 opens a td element and uses Haml’s object reference notation to auto-generate an dom_id attribute for the table cell in the style of city_98, city_99, and so on.
Line 6 opens a div element for the left side of the tile and has the CSS class name needed so that it can be styled properly.
Line 7 calls the image_tag helper to insert a thumbnail photo of the city.
Skipping along, lines 9 – 10 insert the content for the .title div element, in this case, the name and state of the city.
Line 12 directly invokes the description method.
11.23.1.2 Calling the Tiles Partial Code
In order to use this partial, we have to call render :partial with the two required parameters specified in the :locals hash:
1 = render "cities/tiles", cities: @user.cities, columns: 3
I’m guessing that most experienced Rails developers have written some partial code similar to this and tried to figure out a way to include default values for some of the parameters. In this case, it would be really nice to not have to specify :columns all the time, since in most cases we want there to be three.
The problem is that since the parameters are passed via the :locals hash and become local variables, there isn’t an easy way to insert a default value in the partial itself. If you left off the columns: n part of your partial call, Rails would bomb with an exception about columns not being a local variable or method. It’s not the same as an instance variable, which defaults to nil and can be used willy-nilly.
Experienced Rubyists probably know that you can use the defined? method to figure out whether a local variable is in scope or not, but the resulting code would be very ugly. The following code might be considered elegant, but it doesn’t work!64
columns = 3 unless defined? columns
Instead of teaching you how to jump through annoying Ruby idiom hoops, I’ll show you how to tackle this challenge the Rails way, and that is where we can start discussing the helper wrapping technique.
Tim says…
Obie might not want to make you jump through Ruby idiom hoops, but I don’t mind…
11.23.1.3 Write the Helper Method
First, I’ll add a new helper method to the CitiesHelper module of my application, like in Listing 11.7. It’s going to be fairly simple at first. In thinking about the name of the method, it occurs to me that I like the way that tiled(cities) will read instead of tiles(cities), so I name it that way.
Listing 11.7: The CitiesHelper tiled method
1 moduleCitiesHelper
2 def tiled(cities, columns=3)
3 render "cities/tiles", cities: cities, columns: columns
4 end
5 end
Right from the start I can take care of that default columns parameter by giving the helper method parameter for columns a default value. That’s just a normal feature of Ruby. Now instead of specifying the render :partial call in my view template, I can simply write = tiled(cities) which is considerably more elegant and terse. It also serves to decouple the implementation of the tiled city table from the view. If I need to change the way that the tiled table is rendered in the future, I just have to do it in one place: the helper method.
11.23.2 Generalizing Partials
Now that we’ve set the stage, the fun can begin. The first thing we’ll do is move the helper method to the ApplicationHelper module so that it’s available to all view templates. We’ll also move the partial template file to app/views/shared/_tiled_table.html.haml to denote that it isn’t associated with a particular kind of view and to more accurately convey its use. As a matter of good code style, I also do a sweep through the implementation and generalize the identifiers appropriately. The reference to cities on line 2 becomes collection. The block variable city on line 4 becomes item. Listing 11.8 has the new partial code.
Listing 11.8: Tiles partial code with revised naming
1 %table.tiles
2 - collection.in_groups_of(columns) do |row|
3 %tr
4 - row.each do |item|
5 %td[item]
6 .left
7 = image_tag(item.photo.public_filename(:thumb))
8 .right
9 .title
10 = item.name
11 .description
12 = item.description
There’s still the matter of a contract between this partial code and the objects that it is rendering. Namely, they must respond to the following messages: photo, name, and description. A survey of other models in my application reveals that I need more flexibility. Some things have names, but others have titles. Sometimes I want the description to appear under the name of the object represented, but other times I want to be able to insert additional data about the object plus some links.
11.23.2.1 Lambda: the Ultimate Flexibility
Ruby allows you to store references to anonymous methods (also known as procs or lambdas) and call them at will whenever you want.65 Knowing this capability is there, what becomes possible? For starters, we can use lambdas to pass in blocks of code that will fill in parts of our partial dynamically.
For example, the current code for showing the thumbnail is a big problem. Since the code varies greatly depending on the object being handled, I want to be able to pass in instructions for how to get a thumbnail image without having to resort to big if/else statements or putting view logic in my model classes. Please take a moment to understand the problem I’m describing, and then take a look at how we solve it in Listing 11.9. Hint: The thumbnail, link, title, and description variables hold lambdas!
Listing 11.9: Tiles partial code refactored to use lambdas
1 .left
2 = link_to thumbnail.call(item), link.call(item)
3 .right
4 .title
5 = link_to title.call(item), link.call(item)
6 .description
7 = description.call(item)
Notice that in Listing 11.9, the contents of the left and right div elements come from variables containing lambdas. On line 2 we make a call to link_to and both of its arguments are dynamic. A similar construct on line 5 takes care of generating the title link. In both cases, the first lambda should return the output of a call to image_tag and the second should return a URL. In all of these lambda usages, the item currently being rendered is passed to the lambdas as a block variable.
Wilson says…
Things like link.call(item) could potentially look even sassier as link[item], except that you’ll shoot your eye out doing it. (Proc#[] is an alias for Proc#call.)
11.23.2.2 The New Tiled Helper Method
If you now direct your attention to Listing 11.10, you’ll notice that the tiled method is changed considerably. In order to keep my positional argument list down to a manageable size, I’ve switched over to taking a hash of options as the last parameter to the tiled method. This approach is useful and it mimics the way that almost all helper methods take options in Rails.
Default values are provided for all parameters, and they are all passed along to the partial via the :locals hash given to render.
Listing 11.10: The tiled collection helper method with lambda parameters
1 moduleApplicationHelper
2
3 def tiled(collection, opts={})
4 opts[:columns] ||= 3
5
6 opts[:thumbnail] ||= lambda do |item|
7 image_tag(item.photo.url(:thumb))
8 end
9
10 opts[:title] ||= lambda { |item| item.to_s }
11
12 opts[:description] ||= lambda { |item| item.description }
13
14 opts[:link] ||= lambda { |item| item }
15
16 render "shared/tiled_table",
17 collection: collection,
18 columns: opts[:columns],
19 link: opts[:link],
20 thumbnail: opts[:thumbnail],
21 title: opts[:title],
22 description: opts[:description]
23 end
24 end
Finally, to wrap up this example, here’s a snippet showing how to invoke our new tiled helper method from a template, overriding the default behavior for links:
1 tiled(cities, link: lambda { |city| showcase_city_path(city) })
The showcase_city_path method is available to the lambda block, since it is a closure, meaning that it inherits the execution context in which it is created.
11.24 Conclusion
This very long chapter served as a thorough reference of helper methods, both those provided by Rails and ideas for ones that you will write yourself. Effective use of helper methods lead to more elegant and maintainable view templates. At this point you should also have a good overview about how I18n support in Ruby on Rails works and are ready to start translating your project.
Before we fully conclude our coverage of Action View, we’ll jump into the world of Ajax and JavaScript. Arguably, one of the main reasons for Rails’s continued popularity is its support for those two crucial technologies of Web 2.0.
This chapter is published under the Creative Commons Attribution-ShareAlike 4.0 license, http://creativecommons.org/licenses/by-sa/4.0/