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.
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":http://rack.rubyforge.org/ 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:
<shell>
gem install actionpack
gem install rack
</shell>
Now we'll create a simple "Hello World" application that uses the +titleize+ method provided by Action View.
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+:
<ruby>
Post.create(:body => 'Partial Layouts are cool!')
</ruby>
In the +show+ template, we'll render the +post+ partial wrapped in the +box+ layout:
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:
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.
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":form_helpers.html.
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.
This module provides methods for generating HTML that links views to assets such as images, javascripts, 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 your +config/environment.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 additional JavaScript files to be included when +javascript_include_tag :defaults+ is called. This method is typically intended to be called from plugin initialization to register additional +.js+ 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+.
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 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.
To include the Prototype and Scriptaculous javascript libraries 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.
<ruby>
javascript_include_tag :defaults
</ruby>
You can also include all javascripts in the javascripts directory using +:all+ as the source.
<ruby>
javascript_include_tag :all
</ruby>
You can also cache multiple javascripts 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.
You can also include all styles in the stylesheet directory using :all as the source:
<ruby>
stylesheet_link_tag :all
</ruby>
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.
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.
<ruby>
<% benchmark "Process data files" do %>
<%= expensive_files_operation %>
<% end %>
</ruby>
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.
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*
<ruby>
<html>
<head>
<title>Welcome!</title>
<%= yield :special_script %>
</head>
<body>
<p>Welcome! The date and time is <%= Time.now %></p>
Returns a set of select tags (one for year, month, and day) pre-selected for accessing a specified date-based attribute.
<ruby>
date_select("post", "published_on")
</ruby>
h5. datetime_select
Returns a set of select tags (one for year, month, day, hour, and minute) pre-selected for accessing a specified datetime-based attribute.
<ruby>
datetime_select("post", "published_on")
</ruby>
h5. distance_of_time_in_words
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.
<ruby>
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
</ruby>
h5. select_date
Returns a set of html select-tags (one for year, month, and day) pre-selected with the +date+ provided.
<ruby>
# 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()
</ruby>
h5. select_datetime
Returns a set of html select-tags (one for year, month, day, hour, and minute) pre-selected with the +datetime+ provided.
<ruby>
# 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()
</ruby>
h5. select_day
Returns a select tag with options for each of the days 1 through 31 with the current day selected.
<ruby>
# 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)
</ruby>
h5. select_hour
Returns a select tag with options for each of the hours 0 through 23 with the current hour selected.
<ruby>
# Generates a select field for minutes that defaults to the minutes for the time provided
select_minute(Time.now + 6.hours)
</ruby>
h5. select_minute
Returns a select tag with options for each of the minutes 0 through 59 with the current minute selected.
<ruby>
# Generates a select field for minutes that defaults to the minutes for the time provided.
select_minute(Time.now + 6.hours)
</ruby>
h5. select_month
Returns a select tag with options for each of the months January through December with the current month selected.
<ruby>
# Generates a select field for months that defaults to the current month
select_month(Date.today)
</ruby>
h5. select_second
Returns a select tag with options for each of the seconds 0 through 59 with the current second selected.
<ruby>
# Generates a select field for seconds that defaults to the seconds for the time provided
select_second(Time.now + 16.minutes)
</ruby>
h5. select_time
Returns a set of html select-tags (one for hour and minute).
<ruby>
# Generates a time select that defaults to the time provided
select_time(Time.now)
</ruby>
h5. select_year
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+.
<ruby>
# 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
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.
<ruby>
# Creates a time select tag that, when POSTed, will be stored in the order variable in the submitted attribute
time_select("order", "submitted")
</ruby>
h4. Debug Helper
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:
<ruby>
# Note: a @person variable will have been created in the controller (e.g. @person = Person.new)
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 string of option tags for pretty much any country in the world.
h5. country_select
Return select and option tags for the given object and method, using country_options_for_select to generate the list of option tags.
h5. option_groups_from_collection_for_select
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:
Note: Only the +option+ tags are returned, you have to wrap this call in a regular HTML +select+ tag.
h5. options_from_collection_for_select
Returns a string of option tags that have been compiled by iterating over the +collection+ and assigning the the result of a call to the +value_method+ as the option value and the +text_method+ as the option text.
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+:
* September 3, 2009: Continuing work by Trevor Turk, leveraging the "Action Pack docs":http://ap.rubyonrails.org/ and "What's new in Edge Rails":http://ryandaigle.com/articles/2007/8/3/what-s-new-in-edge-rails-partials-get-layouts