1 What is Action View?
Action View and Action Controller are the two major components of Action Pack. In Rails, web requests are handled by Action Pack, which splits the work into a controller part (performing the logic) and a view part (rendering a template). Typically, Action Controller will be concerned with communicating with the database and performing CRUD actions where necessary. Action View is then responsible for compiling the response.
Action View templates are written using embedded Ruby in tags mingled with HTML. To avoid cluttering the templates with boilerplate code, a number of helper classes provide common behavior for forms, dates, and strings. It’s also easy to add new helpers to your application as it evolves.
Note: Some features of Action View are tied to Active Record, but that doesn’t mean that Action View depends on Active Record. Action View is an independent package that can be used with any sort of backend.
2 Using Action View with Rails
For each controller there is an associated directory in the app/views directory which holds the template files that make up the views associated with that controller. These files are used to display the view that results from each controller action.
Let’s take a look at what Rails does by default when creating a new resource using the scaffold generator:
$ rails generate scaffold post [...] invoke scaffold_controller create app/controllers/posts_controller.rb invoke erb create app/views/posts create app/views/posts/index.html.erb create app/views/posts/edit.html.erb create app/views/posts/show.html.erb create app/views/posts/new.html.erb create app/views/posts/_form.html.erb [...]
There is a naming convention for views in Rails. Typically, the views share their name with the associated controller action, as you can see above. For example, the index controller action of the posts_controller.rb will use the index.html.erb view file in the app/views/posts directory. The complete HTML returned to the client is composed of a combination of this ERB file, a layout template that wraps it, and all the partials that the view may reference. Later on this guide you can find a more detailed documentation of each one of this three components.
3 Using Action View outside of Rails
Action View works well with Action Record, but it can also be used with other Ruby tools. We can demonstrate this by creating a small Rack application that includes Action View functionality. This may be useful, for example, if you’d like access to Action View’s helpers in a Rack application.
Let’s start by ensuring that you have the Action Pack and Rack gems installed:
$ gem install actionpack $ gem install rack
Now we’ll create a simple “Hello World” application that uses the titleize method provided by Active Support.
hello_world.rb:
require 'rubygems' require 'active_support/core_ext/string/inflections' require 'rack' def hello_world(env) [200, {"Content-Type" => "text/html"}, "hello world".titleize] end Rack::Handler::Mongrel.run method(:hello_world), :Port => 4567
We can see this all come together by starting up the application and then visiting http://localhost:4567/
$ ruby hello_world.rb
TODO needs a screenshot? I have one – not sure where to put it.
Notice how ‘hello world’ has been converted into ‘Hello World’ by the titleize helper method.
Action View can also be used with Sinatra in the same way.
Let’s start by ensuring that you have the Action Pack and Sinatra gems installed:
$ gem install actionpack $ gem install sinatra
Now we’ll create the same “Hello World” application in Sinatra.
hello_world.rb:
require 'rubygems' require 'action_view' require 'sinatra' get '/' do erb 'hello world'.titleize end
Then, we can run the application:
$ ruby hello_world.rb
Once the application is running, you can see Sinatra and Action View working together by visiting http://localhost:4567/
TODO needs a screenshot? I have one – not sure where to put it.
4 Templates, Partials and Layouts
As mentioned before, the final HTML output is a composition of three Rails elements: Templates, Partials and Layouts. Find below a brief overview of each one of them.
4.1 Templates
Action View templates can be written in several ways. If the template file has a .erb extension then it uses a mixture of ERB (included in Ruby) and HTML. If the template file has a .builder extension then a fresh instance of Builder::XmlMarkup library is used.
Rails supports multiple template systems and uses a file extension to distinguish amongst them. For example, an HTML file using the ERB template system will have .html.erb as a file extension.
4.1.1 ERB
Within an ERB template Ruby code can be included using both <% %> and <%= %> tags. The <% %> are used to execute Ruby code that does not return anything, such as conditions, loops or blocks, and the <%= %> tags are used when you want output.
Consider the following loop for names:
<b>Names of all the people</b> <% @people.each do |person| %> Name: <%= person.name %><br/> <% end %>
The loop is setup in regular embedding tags <% %> and the name is written using the output embedding tag <%= %>. Note that this is not just a usage suggestion, for Regular output functions like print or puts won’t work with ERB templates. So this would be wrong:
<%# WRONG %> Hi, Mr. <% puts "Frodo" %>
To suppress leading and trailing whitespaces, you can use <%- -%> interchangeably with <% and %>.
4.1.2 Builder
Builder templates are a more programmatic alternative to ERB. They are especially useful for generating XML content. An XmlMarkup object named xml is automatically made available to templates with a .builder extension.
Here are some basic examples:
xml.em("emphasized") xml.em { xml.b("emph & bold") } xml.a("A Link", "href"=>"http://rubyonrails.org") xml.target("name"=>"compile", "option"=>"fast")
will produce
<em>emphasized</em> <em><b>emph & bold</b></em> <a href="http://rubyonrails.org">A link</a> <target option="fast" name="compile" />
Any method with a block will be treated as an XML markup tag with nested markup in the block. For example, the following:
xml.div { xml.h1(@person.name) xml.p(@person.bio) }
would produce something like:
<div> <h1>David Heinemeier Hansson</h1> <p>A product of Danish Design during the Winter of '79...</p> </div>
A full-length RSS example actually used on Basecamp:
xml.rss("version" => "2.0", "xmlns:dc" => "http://purl.org/dc/elements/1.1/") do xml.channel do xml.title(@feed_title) xml.link(@url) xml.description "Basecamp: Recent items" xml.language "en-us" xml.ttl "40" for item in @recent_items xml.item do xml.title(item_title(item)) xml.description(item_description(item)) if item_description(item) xml.pubDate(item_pubDate(item)) xml.guid(@person.firm.account.url + @recent_items.url(item)) xml.link(@person.firm.account.url + @recent_items.url(item)) xml.tag!("dc:creator", item.author_name) if item_has_creator?(item) end end end end
4.1.3 Template Caching
By default, Rails will compile each template to a method in order to render it. When you alter a template, Rails will check the file’s modification time and recompile it in development mode.
4.2 Partials
Partial templates – usually just called “partials” – are another device for breaking the rendering process into more manageable chunks. With a partial, you can move the code for rendering a particular piece of a response to its own file.
4.2.1 Naming Partials
To render a partial as part of a view, you use the render method within the view:
<%= render "menu" %>
This will render a file named _menu.html.erb at that point within the view is being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you’re pulling in a partial from another folder:
<%= render "shared/menu" %>
That code will pull in the partial from app/views/shared/_menu.html.erb.
4.2.2 Using Partials to simplify Views
One way to use partials is to treat them as the equivalent of subroutines: as a way to move details out of a view so that you can grasp what’s going on more easily. For example, you might have a view that looked like this:
<%= render "shared/ad_banner" %> <h1>Products</h1> <p>Here are a few of our fine products:</p> <% @products.each do |product| %> <%= render :partial => "product", :locals => { :product => product } %> <% end %> <%= render "shared/footer" %>
Here, the _ad_banner.html.erb and _footer.html.erb partials could contain content that is shared among many pages in your application. You don’t need to see the details of these sections when you’re concentrating on a particular page.
4.2.3 The :as and :object options
By default ActionView::Partials::PartialRenderer has its object in a local variable with the same name as the template. So, given
<%= render :partial => "product" %>
within product we’ll get @product in the local variable product, as if we had written:
<%= render :partial => "product", :locals => { :product => @product } %>
With the :as option we can specify a different name for said local variable. For example, if we wanted it to be item instead of product+ we’d do:
<%= render :partial => "product", :as => 'item' %>
The :object option can be used to directly specify which object is rendered into the partial; useful when the template’s object is elsewhere, in a different ivar or in a local variable for instance.
For example, instead of:
<%= render :partial => "product", :locals => { :product => @item } %>
you’d do:
<%= render :partial => "product", :object => @item %>
The :object and :as options can be used together.
4.2.4 Rendering Collections
The example of partial use describes a familiar pattern where a template needs to iterate over an array and render a sub template for each of the elements. This pattern has been implemented as a single method that accepts an array and renders a partial by the same name as the elements contained within. So the three-lined example for rendering all the products can be rewritten with a single line:
<%= render :partial => "product", :collection => @products %>
When a partial is called with a pluralized collection, then the individual instances of the partial have access to the member of the collection being rendered via a variable named after the partial. In this case, the partial is _product , and within the _product partial, you can refer to product to get the instance that is being rendered.
You can use a shorthand syntax for rendering collections. Assuming @products is a collection of Product instances, you can simply write the following to produce the same result:
<%= render @products %>
Rails determines the name of the partial to use by looking at the model name in the collection. In fact, you can even create a heterogeneous collection and render it this way, and Rails will choose the proper partial for each member of the collection.
4.2.5 Spacer Templates
You can also specify a second partial to be rendered between instances of the main partial by using the :spacer_template option:
<%= render @products, :spacer_template => "product_ruler" %>
Rails will render the _product_ruler partial (with no data passed in to it) between each pair of _product partials.
4.3 Layouts
TODO…
5 Using Templates, Partials and Layouts in “The Rails Way”
TODO…
6 Partial Layouts
Partials can have their own layouts applied to them. These layouts are different than the ones that are specified globally for the entire action, but they work in a similar fashion.
Let’s say we’re displaying a post on a page where it should be wrapped in a div for display purposes. First, we’ll create a new Post:
Post.create(:body => 'Partial Layouts are cool!')
In the show template, we’ll render the post partial wrapped in the box layout:
posts/show.html.erb
<%= render :partial => 'post', :layout => 'box', :locals => {:post => @post} %>
The box layout simply wraps the post partial in a div:
posts/_box.html.erb
<div class='box'> <%= yield %> </div>
The post partial wraps the post’s body in a div with the id of the post using the div_for helper:
posts/_post.html.erb
<%= div_for(post) do %> <p><%= post.body %></p> <% end %>
This example would output the following:
<div class='box'> <div id='post_1'> <p>Partial Layouts are cool!</p> </div> </div>
Note that the partial layout has access to the local post variable that was passed into the render call. However, unlike application-wide layouts, partial layouts still have the underscore prefix.
You can also render a block of code within a partial layout instead of calling yield. For example, if we didn’t have the post partial, we could do this instead:
posts/show.html.erb
<% render(:layout => 'box', :locals => {:post => @post}) do %> <%= div_for(post) do %> <p><%= post.body %></p> <% end %> <% end %>
If we’re using the same box partial from above, his would produce the same output as the previous example.
7 View Paths
TODO…
8 Overview of all the helpers provided by Action View
The following is only a brief overview summary of the helpers available in Action View. It’s recommended that you review the API Documentation, which covers all of the helpers in more detail, but this should serve as a good starting point.
8.1 ActiveRecordHelper
The Active Record Helper makes it easier to create forms for records kept in instance variables. You may also want to review the Rails Form helpers guide.
8.1.1 error_message_on
Returns a string containing the error message attached to the method on the object if one exists.
error_message_on "post", "title"
8.1.2 error_messages_for
Returns a string with a DIV containing all of the error messages for the objects located as instance variables by the names given.
error_messages_for "post"
8.1.3 form
Returns a form with inputs for all attributes of the specified Active Record object. For example, let’s say we have a @post with attributes named title of type String and body of type Text. Calling form would produce a form to creating a new post with inputs for those attributes.
form("post")
<form action='/posts/create' method='post'> <p> <label for="post_title">Title</label><br /> <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" /> </p> <p> <label for="post_body">Body</label><br /> <textarea cols="40" id="post_body" name="post[body]" rows="20"></textarea> </p> <input name="commit" type="submit" value="Create" /> </form>
Typically, form_for is used instead of form because it doesn’t automatically include all of the model’s attributes.
8.1.4 input
Returns a default input tag for the type of object returned by the method.
For example, if @post has an attribute title mapped to a String column that holds “Hello World”:
input("post", "title") # => <input id="post_title" name="post[title]" size="30" type="text" value="Hello World" />
8.2 RecordTagHelper
This module provides methods for generating a container tag, such as a Renders a container tag that relates to your Active Record Object. For example, given @post is the object of Post class, you can do: This will generate this HTML output: You can also supply HTML attributes as an additional option hash. For example: Will generate this HTML output: You can pass a collection of Active Record objects. This method will loop through your objects and create a container for each of them. For example, given @posts is an array of two Post objects: Will generate this HTML output: This is actually a convenient method which calls content_tag_for internally with :div as the tag name. You can pass either an Active Record object or a collection of objects. For example: Will generate this HTML output: This module provides methods for generating HTML that links views to assets such as images, JavaScript files, stylesheets, and feeds. By default, Rails links to these assets on the current host in the public folder, but you can direct Rails to link to assets from a dedicated assets server by setting ActionController::Base.asset_host in the application configuration, typically in config/environments/production.rb. For example, let’s say your asset host is assets.example.com: Register one or more JavaScript files to be included when symbol is passed to javascript_include_tag. This method is typically intended to be called from plugin initialization to register JavaScript files that the plugin installed in public/javascripts. Register one or more stylesheet files to be included when symbol is passed to stylesheet_link_tag. This method is typically intended to be called from plugin initialization to register stylesheet files that the plugin installed in public/stylesheets. Returns a link tag that browsers and news readers can use to auto-detect an RSS or ATOM feed. Computes the path to an image asset in the public/images directory. Full paths from the document root will be passed through. Used internally by image_tag to build the image path. Returns an html image tag for the source. The source can be a full path or a file that exists in your public/images directory. Returns an html script tag for each of the sources provided. You can pass in the filename (.js extension is optional) of JavaScript files that exist in your public/javascripts directory for inclusion into the current page or you can pass the full path relative to your document root. If the application does not use the asset pipeline, to include the jQuery JavaScript library in your application, pass :defaults as the source. When using :defaults, if an application.js file exists in your public/javascripts directory, it will be included as well. You can also include all JavaScript files in the public/javascripts directory using :all as the source. You can also cache multiple JavaScript files into one file, which requires less HTTP connections to download and can better be compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching is set to true (which is the case by default for the Rails production environment, but not for the development environment). Computes the path to a JavaScript asset in the public/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. Returns a stylesheet link tag for the sources specified as arguments. If you don’t specify an extension, .css will be appended automatically. You can also include all styles in the stylesheet directory using :all as the source: You can also cache multiple stylesheets into one file, which requires less HTTP connections and can better be compressed by gzip (leading to faster transfers). Caching will only happen if ActionController::Base.perform_caching is set to true (which is the case by default for the Rails production environment, but not for the development environment). Computes the path to a stylesheet asset in the public/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. This helper makes building an ATOM feed easy. Here’s a full usage example: config/routes.rb app/controllers/posts_controller.rb app/views/posts/index.atom.builder Allows you to measure the execution time of a block in a template and records the result to the log. Wrap this block around expensive operations or possible bottlenecks to get a time reading for the operation. This would add something like “Process data files (0.34523)” to the log, which you can then use to compare timings when optimizing your code. A method for caching fragments of a view rather than an entire action or page. This technique is useful caching pieces like menus, lists of news topics, static HTML fragments, and so on. This method takes a block that contains the content you wish to cache. See ActionController::Caching::Fragments for more information. The capture method allows you to extract part of a template into a variable. You can then use this variable anywhere in your templates or layout. The captured variable can then be used anywhere else. Calling content_for stores a block of markup in an identifier for later use. You can make subsequent calls to the stored content in other templates or the layout by passing the identifier as an argument to yield. For example, let’s say we have a standard application layout, but also a special page that requires certain Javascript that the rest of the site doesn’t need. We can use content_for to include this Javascript on our special page without fattening up the rest of the site. app/views/layouts/application.html.erb app/views/posts/special.html.erb Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute. Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based attribute. Reports the approximate distance in time between two Time or Date objects or integers as seconds. Set include_seconds to true if you want more detailed approximations. Returns a set of html select-tags (one for year, month, and day) pre-selected with the date provided. Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the datetime provided. Returns a select tag with options for each of the days 1 through 31 with the current day selected. Returns a select tag with options for each of the hours 0 through 23 with the current hour selected. Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected. Returns a select tag with options for each of the months January through December with the current month selected. Returns a select tag with options for each of the seconds 0 through 59 with the current second selected. Returns a set of html select-tags (one for hour and minute). Returns a select tag with options for each of the five years on each side of the current, which is selected. The five year radius can be changed using the :start_year and :end_year keys in the options. Like distance_of_time_in_words, but where to_time is fixed to Time.now. Returns a set of select tags (one for hour, minute and optionally second) pre-selected for accessing a specified time-based attribute. The selects are prepared for multi-parameter assignment to an Active Record object. Returns a pre tag that has object dumped by YAML. This creates a very readable way to inspect an object. Form helpers are designed to make working with models much easier compared to using just standard HTML elements by providing a set of methods for creating forms based on your models. This helper generates the HTML for forms, providing a method for each sort of input (e.g., text, password, select, and so on). When the form is submitted (i.e., when the user hits the submit button or form.submit is called via JavaScript), the form inputs will be bundled into the params object and passed back to the controller. There are two types of form helpers: those that specifically work with model attributes and those that don’t. This helper deals with those that work with model attributes; to see an example of form helpers that don’t work with model attributes, check the ActionView::Helpers::FormTagHelper documentation. The core method of this helper, form_for, gives you the ability to create a form for a model instance; for example, let’s say that you have a model Person and want to create a new instance of it: The HTML generated for this would be: The params object created when this form is submitted would look like: The params hash has a nested person value, which can therefore be accessed with params[:person] in the controller. Returns a checkbox tag tailored for accessing a specified attribute. Creates a scope around a specific model object like form_for, but doesn’t create the form tags themselves. This makes fields_for suitable for specifying additional model objects in the same form: Returns a file upload input tag tailored for accessing a specified attribute. Creates a form and a scope around a specific model object that is used as a base for questioning about values for the fields. Returns a hidden input tag tailored for accessing a specified attribute. Returns a label tag tailored for labelling an input field for a specified attribute. Returns an input tag of the “password” type tailored for accessing a specified attribute. Returns a radio button tag for accessing a specified attribute. Returns a textarea opening and closing tag set tailored for accessing a specified attribute. Returns an input tag of the “text” type tailored for accessing a specified attribute. Provides a number of methods for turning different kinds of containers into a set of option tags. Returns select and option tags for the collection of existing return values of method for object’s class. Example object structure for use with this method: Sample usage (selecting the associated Author for an instance of Post, @post): If @post.author_id is 1, this would return: Returns a string of option tags for pretty much any country in the world. Return select and option tags for the given object and method, using country_options_for_select to generate the list of option tags. Returns a string of option tags, like options_from_collection_for_select, but groups them by optgroup tags based on the object relationships of the arguments. Example object structure for use with this method: Sample usage: Possible output: Note: Only the optgroup and option tags are returned, so you still have to wrap the output in an appropriate select tag. Accepts a container (hash, array, enumerable, your type) and returns a string of option tags. Note: Only the option tags are returned, you have to wrap this call in a regular HTML select tag. 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. For example, imagine a loop iterating over each person in @project.people to generate an input tag: Note: Only the option tags are returned, you have to wrap this call in a regular HTML select tag. Create a select tag and a series of contained option tags for the provided object and method. Example: If @post.person_id is 1, this would become: Returns a string of option tags for pretty much any time zone in the world. Return select and option tags for the given object and method, using time_zone_options_for_select to generate the list of option tags. Provides a number of methods for creating form tags that doesn’t rely on an Active Record object assigned to the template like FormHelper does. Instead, you provide the names and values manually. Creates a check box form input tag. Creates a field set for grouping HTML form elements. Creates a file upload field. Prior to Rails 3.1, if you are using file uploads, then you will need to set the multipart option for the form tag. Rails 3.1+ does this automatically. Example output: Starts a form tag that points the action to an url configured with url_for_options just like ActionController::Base#url_for. Creates a hidden form input field used to transmit data that would be lost due to HTTP’s statelessness or data that should be hidden from the user. Displays an image which when clicked will submit the form. Creates a label field. Creates a password field, a masked text field that will hide the users input behind a mask character. Creates a radio button; use groups of radio buttons named the same to allow users to select from a group of options. Creates a dropdown selection box. Creates a submit button with the text provided as the caption. Creates a text input area; use a textarea for longer text inputs such as blog posts or descriptions. Creates a standard text field; use these text fields to input smaller chunks of text like a username or a search query. Provides functionality for working with JavaScript in your views. Returns a button that’ll trigger a JavaScript function using the onclick handler. Examples: Includes the Action Pack JavaScript libraries inside a single script tag. Escape carrier returns and single and double quotes for JavaScript segments. Returns a JavaScript tag wrapping the provided code. Returns a link that will trigger a JavaScript function using the onclick handler and return false after the fact. Provides methods for converting numbers into formatted strings. Methods are provided for phone numbers, currency, percentage, precision, positional notation, and file size. Formats a number into a currency string (e.g., $13.65). Formats the bytes in size into a more understandable representation; useful for reporting file sizes to users. Formats a number as a percentage string. Formats a number into a US phone number. Formats a number with grouped thousands using a delimiter. Formats a number with the specified level of precision, which defaults to 3. Action View has the ability render different templates depending on the current locale. For example, suppose you have a Posts controller with a show action. By default, calling this action will render app/views/posts/show.html.erb. But if you set I18n.locale = :de, then app/views/posts/show.de.html.erb will be rendered instead. If the localized template isn’t present, the undecorated version will be used. This means you’re not required to provide localized views for all cases, but they will be preferred and used if available. You can use the same technique to localize the rescue files in your public directory. For example, setting I18n.locale = :de and creating public/500.de.html and public/404.de.html would allow you to have localized rescue pages. Since Rails doesn’t restrict the symbols that you use to set I18n.locale, you can leverage this system to display different content depending on anything you like. For example, suppose you have some “expert” users that should see different pages from “normal” users. You could add the following to app/controllers/application.rb: Then you could create special views like app/views/posts/show.expert.html.erb that would only be displayed to expert users. You can read more about the Rails Internationalization (I18n) API here.
You're encouraged to help improve the quality of this guide.
If you see any typos or factual errors you are confident to
patch, please clone docrails
and push the change yourself. That branch of Rails has public write access.
Commits are still reviewed, but that happens after you've submitted your
contribution. docrails is
cross-merged with master periodically.
You may also find incomplete content, or stuff that is not up to date.
Please do add any missing documentation for master. Check the
Ruby on Rails Guides Guidelines
for style and conventions.
If for whatever reason you spot something to fix but cannot patch it yourself, please
open an issue.
And last but not least, any kind of discussion regarding Ruby on Rails
documentation is very welcome in the rubyonrails-docs mailing list.
8.2.1 content_tag_for
<%= content_tag_for(:tr, @post) do %>
<td><%= @post.title %></td>
<% end %>
<tr id="post_1234" class="post">
<td>Hello World!</td>
</tr>
<%= content_tag_for(:tr, @post, :class => "frontpage") do %>
<td><%= @post.title %></td>
<% end %>
<tr id="post_1234" class="post frontpage">
<td>Hello World!</td>
</tr>
<%= content_tag_for(:tr, @posts) do |post| %>
<td><%= post.title %></td>
<% end %>
<tr id="post_1234" class="post">
<td>Hello World!</td>
</tr>
<tr id="post_1235" class="post">
<td>Ruby on Rails Rocks!</td>
</tr>
8.2.2 div_for
<%= div_for(@post, :class => "frontpage") do %>
<td><%= @post.title %></td>
<% end %>
<div id="post_1234" class="post frontpage">
<td>Hello World!</td>
</div>
8.3 AssetTagHelper
ActionController::Base.asset_host = "assets.example.com"
image_tag("rails.png") # => <img src="http://assets.example.com/images/rails.png" alt="Rails" />
8.3.1 register_javascript_expansion
ActionView::Helpers::AssetTagHelper.register_javascript_expansion :monkey => ["head", "body", "tail"]
javascript_include_tag :monkey # =>
<script type="text/javascript" src="/javascripts/head.js"></script>
<script type="text/javascript" src="/javascripts/body.js"></script>
<script type="text/javascript" src="/javascripts/tail.js"></script>
8.3.2 register_stylesheet_expansion
ActionView::Helpers::AssetTagHelper.register_stylesheet_expansion :monkey => ["head", "body", "tail"]
stylesheet_link_tag :monkey # =>
<link href="/stylesheets/head.css" media="screen" rel="stylesheet" type="text/css" />
<link href="/stylesheets/body.css" media="screen" rel="stylesheet" type="text/css" />
<link href="/stylesheets/tail.css" media="screen" rel="stylesheet" type="text/css" />
8.3.3 auto_discovery_link_tag
auto_discovery_link_tag(:rss, "http://www.example.com/feed.rss", {:title => "RSS Feed"}) # =>
<link rel="alternate" type="application/rss+xml" title="RSS Feed" href="http://www.example.com/feed" />
8.3.4 image_path
image_path("edit.png") # => /images/edit.png
8.3.5 image_tag
image_tag("icon.png") # => <img src="/images/icon.png" alt="Icon" />
8.3.6 javascript_include_tag
javascript_include_tag "common" # =>
<script type="text/javascript" src="/javascripts/common.js"></script>
javascript_include_tag :defaults
javascript_include_tag :all
javascript_include_tag :all, :cache => true # =>
<script type="text/javascript" src="/javascripts/all.js"></script>
8.3.7 javascript_path
javascript_path "common" # => /javascripts/common.js
8.3.8 stylesheet_link_tag
stylesheet_link_tag "application" # =>
<link href="/stylesheets/application.css" media="screen" rel="stylesheet" type="text/css" />
stylesheet_link_tag :all
stylesheet_link_tag :all, :cache => true
<link href="/stylesheets/all.css" media="screen" rel="stylesheet" type="text/css" />
8.3.9 stylesheet_path
stylesheet_path "application" # => /stylesheets/application.css
8.4 AtomFeedHelper
8.4.1 atom_feed
resources :posts
def index
@posts = Post.all
respond_to do |format|
format.html
format.atom
end
end
atom_feed do |feed|
feed.title("Posts Index")
feed.updated((@posts.first.created_at))
@posts.each do |post|
feed.entry(post) do |entry|
entry.title(post.title)
entry.content(post.body, :type => 'html')
entry.author do |author|
author.name(post.author_name)
end
end
end
end
8.5 BenchmarkHelper
8.5.1 benchmark
<% benchmark "Process data files" do %>
<%= expensive_files_operation %>
<% end %>
8.6 CacheHelper
8.6.1 cache
<% cache do %>
<%= render "shared/footer" %>
<% end %>
8.7 CaptureHelper
8.7.1 capture
<% @greeting = capture do %>
<p>Welcome! The date and time is <%= Time.now %></p>
<% end %>
<html>
<head>
<title>Welcome!</title>
</head>
<body>
<%= @greeting %>
</body>
</html>
8.7.2 content_for
<html>
<head>
<title>Welcome!</title>
<%= yield :special_script %>
</head>
<body>
<p>Welcome! The date and time is <%= Time.now %></p>
</body>
</html>
<p>This is a special page.</p>
<% content_for :special_script do %>
<script type="text/javascript">alert('Hello!')</script>
<% end %>
8.8 DateHelper
8.8.1 date_select
date_select("post", "published_on")
8.8.2 datetime_select
datetime_select("post", "published_on")
8.8.3 distance_of_time_in_words
distance_of_time_in_words(Time.now, Time.now + 15.seconds) # => less than a minute
distance_of_time_in_words(Time.now, Time.now + 15.seconds, true) # => less than 20 seconds
8.8.4 select_date
# Generates a date select that defaults to the date provided (six days after today)
select_date(Time.today + 6.days)
# Generates a date select that defaults to today (no specified date)
select_date()
8.8.5 select_datetime
# Generates a datetime select that defaults to the datetime provided (four days after today)
select_datetime(Time.now + 4.days)
# Generates a datetime select that defaults to today (no specified datetime)
select_datetime()
8.8.6 select_day
# Generates a select field for days that defaults to the day for the date provided
select_day(Time.today + 2.days)
# Generates a select field for days that defaults to the number given
select_day(5)
8.8.7 select_hour
# Generates a select field for minutes that defaults to the minutes for the time provided
select_minute(Time.now + 6.hours)
8.8.8 select_minute
# Generates a select field for minutes that defaults to the minutes for the time provided.
select_minute(Time.now + 6.hours)
8.8.9 select_month
# Generates a select field for months that defaults to the current month
select_month(Date.today)
8.8.10 select_second
# Generates a select field for seconds that defaults to the seconds for the time provided
select_second(Time.now + 16.minutes)
8.8.11 select_time
# Generates a time select that defaults to the time provided
select_time(Time.now)
8.8.12 select_year
# Generates a select field for five years on either side of Date.today that defaults to the current year
select_year(Date.today)
# Generates a select field from 1900 to 2009 that defaults to the current year
select_year(Date.today, :start_year => 1900, :end_year => 2009)
8.8.13 time_ago_in_words
time_ago_in_words(3.minutes.from_now) # => 3 minutes
8.8.14 time_select
# Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute
time_select("order", "submitted")
8.9 DebugHelper
my_hash = {'first' => 1, 'second' => 'two', 'third' => [1,2,3]}
debug(my_hash)
<pre class='debug_dump'>---
first: 1
second: two
third:
- 1
- 2
- 3
</pre>
8.10 FormHelper
# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
<%= form_for @person, :url => { :action => "create" } do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= submit_tag 'Create' %>
<% end %>
<form action="/persons/create" method="post">
<input id="person_first_name" name="person[first_name]" size="30" type="text" />
<input id="person_last_name" name="person[last_name]" size="30" type="text" />
<input name="commit" type="submit" value="Create" />
</form>
{"action"=>"create", "controller"=>"persons", "person"=>{"first_name"=>"William", "last_name"=>"Smith"}}
8.10.1 check_box
# Let's say that @post.validated? is 1:
check_box("post", "validated")
# => <input type="checkbox" id="post_validated" name="post[validated]" value="1" />
# <input name="post[validated]" type="hidden" value="0" />
8.10.2 fields_for
<%= form_for @person, :url => { :action => "update" } do |person_form| %>
First name: <%= person_form.text_field :first_name %>
Last name : <%= person_form.text_field :last_name %>
<%= fields_for @person.permission do |permission_fields| %>
Admin? : <%= permission_fields.check_box :admin %>
<% end %>
<% end %>
8.10.3 file_field
file_field(:user, :avatar)
# => <input type="file" id="user_avatar" name="user[avatar]" />
8.10.4 form_for
<%= form_for @post do |f| %>
<%= f.label :title, 'Title' %>:
<%= f.text_field :title %><br />
<%= f.label :body, 'Body' %>:
<%= f.text_area :body %><br />
<% end %>
8.10.5 hidden_field
hidden_field(:user, :token)
# => <input type="hidden" id="user_token" name="user[token]" value="#{@user.token}" />
8.10.6 label
label(:post, :title)
# => <label for="post_title">Title</label>
8.10.7 password_field
password_field(:login, :pass)
# => <input type="text" id="login_pass" name="login[pass]" value="#{@login.pass}" />
8.10.8 radio_button
# Let's say that @post.category returns "rails":
radio_button("post", "category", "rails")
radio_button("post", "category", "java")
# => <input type="radio" id="post_category_rails" name="post[category]" value="rails" checked="checked" />
# <input type="radio" id="post_category_java" name="post[category]" value="java" />
8.10.9 text_area
text_area(:comment, :text, :size => "20x30")
# => <textarea cols="20" rows="30" id="comment_text" name="comment[text]">
# #{@comment.text}
# </textarea>
8.10.10 text_field
text_field(:post, :title)
# => <input type="text" id="post_title" name="post[title]" value="#{@post.title}" />
8.11 FormOptionsHelper
8.11.1 collection_select
class Post < ActiveRecord::Base
belongs_to :author
end
class Author < ActiveRecord::Base
has_many :posts
def name_with_initial
"#{first_name.first}. #{last_name}"
end
end
collection_select(:post, :author_id, Author.all, :id, :name_with_initial, {:prompt => true})
<select name="post[author_id]">
<option value="">Please select</option>
<option value="1" selected="selected">D. Heinemeier Hansson</option>
<option value="2">D. Thomas</option>
<option value="3">M. Clark</option>
</select>
8.11.2 country_options_for_select
8.11.3 country_select
8.11.4 option_groups_from_collection_for_select
class Continent < ActiveRecord::Base
has_many :countries
# attribs: id, name
end
class Country < ActiveRecord::Base
belongs_to :continent
# attribs: id, name, continent_id
end
option_groups_from_collection_for_select(@continents, :countries, :name, :id, :name, 3)
<optgroup label="Africa">
<option value="1">Egypt</option>
<option value="4">Rwanda</option>
...
</optgroup>
<optgroup label="Asia">
<option value="3" selected="selected">China</option>
<option value="12">India</option>
<option value="5">Japan</option>
...
</optgroup>
8.11.5 options_for_select
options_for_select([ "VISA", "MasterCard" ])
# => <option>VISA</option> <option>MasterCard</option>
8.11.6 options_from_collection_for_select
# options_from_collection_for_select(collection, value_method, text_method, selected = nil)
options_from_collection_for_select(@project.people, "id", "name")
# => <option value="#{person.id}">#{person.name}</option>
8.11.7 select
select("post", "person_id", Person.all.collect {|p| [ p.name, p.id ] }, { :include_blank => true })
<select name="post[person_id]">
<option value=""></option>
<option value="1" selected="selected">David</option>
<option value="2">Sam</option>
<option value="3">Tobias</option>
</select>
8.11.8 time_zone_options_for_select
8.11.9 time_zone_select
time_zone_select( "user", "time_zone")
8.12 FormTagHelper
8.12.1 check_box_tag
check_box_tag 'accept'
# => <input id="accept" name="accept" type="checkbox" value="1" />
8.12.2 field_set_tag
<%= field_set_tag do %>
<p><%= text_field_tag 'name' %></p>
<% end %>
# => <fieldset><p><input id="name" name="name" type="text" /></p></fieldset>
8.12.3 file_field_tag
<%= form_tag { :action => "post" }, { :multipart => true } do %>
<label for="file">File to Upload</label> <%= file_field_tag "file" %>
<%= submit_tag %>
<% end %>
file_field_tag 'attachment'
# => <input id="attachment" name="attachment" type="file" />
8.12.4 form_tag
<%= form_tag '/posts' do %>
<div><%= submit_tag 'Save' %></div>
<% end %>
# => <form action="/posts" method="post"><div><input type="submit" name="submit" value="Save" /></div></form>
8.12.5 hidden_field_tag
hidden_field_tag 'token', 'VUBJKB23UIVI1UU1VOBVI@'
# => <input id="token" name="token" type="hidden" value="VUBJKB23UIVI1UU1VOBVI@" />
8.12.6 image_submit_tag
image_submit_tag("login.png")
# => <input src="/images/login.png" type="image" />
8.12.7 label_tag
label_tag 'name'
# => <label for="name">Name</label>
8.12.8 password_field_tag
password_field_tag 'pass'
# => <input id="pass" name="pass" type="password" />
8.12.9 radio_button_tag
radio_button_tag 'gender', 'male'
# => <input id="gender_male" name="gender" type="radio" value="male" />
8.12.10 select_tag
select_tag "people", "<option>David</option>"
# => <select id="people" name="people"><option>David</option></select>
8.12.11 submit_tag
submit_tag "Publish this post"
# => <input name="commit" type="submit" value="Publish this post" />
8.12.12 text_area_tag
text_area_tag 'post'
# => <textarea id="post" name="post"></textarea>
8.12.13 text_field_tag
text_field_tag 'name'
# => <input id="name" name="name" type="text" />
8.13 JavaScriptHelper
8.13.1 button_to_function
button_to_function "Greeting", "alert('Hello world!')"
button_to_function "Delete", "if (confirm('Really?')) do_delete()"
button_to_function "Details" do |page|
page[:details].visual_effect :toggle_slide
end
8.13.2 define_javascript_functions
8.13.3 escape_javascript
8.13.4 javascript_tag
javascript_tag "alert('All is good')"
<script type="text/javascript">
//<![CDATA[
alert('All is good')
//]]>
</script>
8.13.5 link_to_function
link_to_function "Greeting", "alert('Hello world!')"
# => <a onclick="alert('Hello world!'); return false;" href="#">Greeting</a>
8.14 NumberHelper
8.14.1 number_to_currency
number_to_currency(1234567890.50) # => $1,234,567,890.50
8.14.2 number_to_human_size
number_to_human_size(1234) # => 1.2 KB
number_to_human_size(1234567) # => 1.2 MB
8.14.3 number_to_percentage
number_to_percentage(100, :precision => 0) # => 100%
8.14.4 number_to_phone
number_to_phone(1235551234) # => 123-555-1234
8.14.5 number_with_delimiter
number_with_delimiter(12345678) # => 12,345,678
8.14.6 number_with_precision
number_with_precision(111.2345) # => 111.235
number_with_precision(111.2345, 2) # => 111.23
9 Localized Views
before_filter :set_expert_locale
def set_expert_locale
I18n.locale = :expert if current_user.expert?
end
Feedback