CINXE.COM

Layouts and Rendering in Rails — Ruby on Rails Guides

<!doctype html> <html dir="ltr" lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Layouts and Rendering in Rails — Ruby on Rails Guides</title> <link rel="stylesheet" type="text/css" href="stylesheets/style-071e355820fc155a5c40ef8a1c0c4971.css" data-turbo-track="reload"> <link rel="stylesheet" type="text/css" href="stylesheets/print-a87ee66d50ce96bb83ac082f1249fe3e.css" media="print"> <link rel="stylesheet" type="text/css" href="stylesheets/highlight-a0d2133dd0073968b2d33b1f1360a2a3.css" data-turbo-track="reload"> <link rel="icon" href="images/favicon.ico" sizes="any"> <link rel="apple-touch-icon" href="images/icon.png"> <script src="javascripts/@hotwired--turbo-764f59c7edbeb902a9068c0340dd274e.js" data-turbo-track="reload"></script> <script src="javascripts/clipboard-8b7aed6f069f0cf58eeae353cd2f898b.js" data-turbo-track="reload"></script> <script src="javascripts/guides-897790ae3777ddd81bd4953f7ec99835.js" data-turbo-track="reload"></script> <meta property="og:title" content="Layouts and Rendering in Rails — Ruby on Rails Guides" /> <meta name="description" content="Layouts and Rendering in RailsThis guide covers the basic layout features of Action Controller and Action View.After reading this guide, you will know: How to use the various rendering methods built into Rails. How to create layouts with multiple content sections. How to use partials to DRY up your views. How to use nested layouts (sub-templates)." /> <meta property="og:description" content="Layouts and Rendering in RailsThis guide covers the basic layout features of Action Controller and Action View.After reading this guide, you will know: How to use the various rendering methods built into Rails. How to create layouts with multiple content sections. How to use partials to DRY up your views. How to use nested layouts (sub-templates)." /> <meta property="og:locale" content="en_US" /> <meta property="og:site_name" content="Ruby on Rails Guides" /> <meta property="og:image" content="https://avatars.githubusercontent.com/u/4223" /> <meta property="og:type" content="website" /> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css2?family=Heebo:wght@100..900&family=Noto+Sans+Arabic:wght@100..900&display=swap" rel="stylesheet"> <meta name="theme-color" content="#C81418"> </head> <body dir="ltr" class="guide no-js"> <script> document.body.classList.remove('no-js') </script> <a id="main-skip-link" href="#main" class="skip-link" data-turbo="false"> Skip to main content </a> <div id="mobile-navigation-bar"> <div class="wrapper"> <strong class="more-info-label">More at <a href="https://rubyonrails.org/">rubyonrails.org:</a> </strong> <button type="button" class="js-only red-button more-info-button" id="more-info" aria-controls="more-info-links" aria-expanded="false"> More Ruby on Rails </button> <ul id="more-info-links" class="more-info-links hidden"> <li class="more-info"><a href="https://rubyonrails.org/blog">Blog</a></li> <li class="more-info"><a href="https://guides.rubyonrails.org/">Guides</a></li> <li class="more-info"><a href="https://api.rubyonrails.org/">API</a></li> <li class="more-info"><a href="https://discuss.rubyonrails.org/">Forum</a></li> <li class="more-info"><a href="https://github.com/rails/rails">Contribute on GitHub</a></li> </ul> </div> </div> <header id="page-header"> <div class="wrapper clearfix"> <nav id="feature-nav"> <div class="header-logo"> <a href="index.html" title="Guides home for v8.0.0 Guides">Guides</a> <span id="version-switcher" class="js-only"> <label for="version-switcher-select">Version: <span class="visibly-hidden">pick from the list to go to that Rails version's guides</span></label> <select id="version-switcher-select" class="guides-version"> <option value="https://edgeguides.rubyonrails.org/">Edge</option> <option value="https://guides.rubyonrails.org/v8.0/" selected>8.0</option> <option value="https://guides.rubyonrails.org/v7.2/">7.2</option> <option value="https://guides.rubyonrails.org/v7.1/">7.1</option> <option value="https://guides.rubyonrails.org/v7.0/">7.0</option> <option value="https://guides.rubyonrails.org/v6.1/">6.1</option> <option value="https://guides.rubyonrails.org/v6.0/">6.0</option> <option value="https://guides.rubyonrails.org/v5.2/">5.2</option> <option value="https://guides.rubyonrails.org/v5.1/">5.1</option> <option value="https://guides.rubyonrails.org/v5.0/">5.0</option> <option value="https://guides.rubyonrails.org/v4.2/">4.2</option> <option value="https://guides.rubyonrails.org/v4.1/">4.1</option> <option value="https://guides.rubyonrails.org/v4.0/">4.0</option> <option value="https://guides.rubyonrails.org/v3.2/">3.2</option> <option value="https://guides.rubyonrails.org/v3.1/">3.1</option> <option value="https://guides.rubyonrails.org/v3.0/">3.0</option> <option value="https://guides.rubyonrails.org/v2.3/">2.3</option> </select> </span> </div> <ul class="nav"> <li><a class="nav-item" id="home_nav" href="https://rubyonrails.org/">Home</a></li> <li class="guides-index guides-index-large"> <a href="index.html" id="guides-menu-button" data-aria-controls="guides" data-aria-expanded="false" class="guides-index-item nav-item">Guides Index</a> <div id="guides" class="clearfix" style="display: none;"> <hr /> <dl class="guides-section-container"> <div class="guides-section"> <dt>Start Here</dt> <dd><a href="getting_started.html">Getting Started with Rails</a></dd> </div> <div class="guides-section"> <dt>Models</dt> <dd><a href="active_record_basics.html">Active Record Basics</a></dd> <dd><a href="active_record_migrations.html">Active Record Migrations</a></dd> <dd><a href="active_record_validations.html">Active Record Validations</a></dd> <dd><a href="active_record_callbacks.html">Active Record Callbacks</a></dd> <dd><a href="association_basics.html">Active Record Associations</a></dd> <dd><a href="active_record_querying.html">Active Record Query Interface</a></dd> <dd><a href="active_model_basics.html">Active Model Basics</a></dd> </div> <div class="guides-section"> <dt>Views</dt> <dd><a href="action_view_overview.html">Action View Overview</a></dd> <dd><a href="layouts_and_rendering.html">Layouts and Rendering in Rails</a></dd> <dd><a href="action_view_helpers.html">Action View Helpers</a></dd> <dd><a href="form_helpers.html">Action View Form Helpers</a></dd> </div> <div class="guides-section"> <dt>Controllers</dt> <dd><a href="action_controller_overview.html">Action Controller Overview</a></dd> <dd><a href="routing.html">Rails Routing from the Outside In</a></dd> </div> <div class="guides-section"> <dt>Other Components</dt> <dd><a href="active_support_core_extensions.html">Active Support Core Extensions</a></dd> <dd><a href="action_mailer_basics.html">Action Mailer Basics</a></dd> <dd><a href="action_mailbox_basics.html">Action Mailbox Basics</a></dd> <dd><a href="action_text_overview.html">Action Text Overview</a></dd> <dd><a href="active_job_basics.html">Active Job Basics</a></dd> <dd><a href="active_storage_overview.html">Active Storage Overview</a></dd> <dd><a href="action_cable_overview.html">Action Cable Overview</a></dd> </div> <div class="guides-section"> <dt>Digging Deeper</dt> <dd><a href="i18n.html">Rails Internationalization (I18n) API</a></dd> <dd><a href="testing.html">Testing Rails Applications</a></dd> <dd><a href="security.html">Securing Rails Applications</a></dd> <dd><a href="error_reporting.html">Error Reporting in Rails Applications</a></dd> <dd><a href="debugging_rails_applications.html">Debugging Rails Applications</a></dd> <dd><a href="configuring.html">Configuring Rails Applications</a></dd> <dd><a href="command_line.html">The Rails Command Line</a></dd> <dd><a href="asset_pipeline.html">The Asset Pipeline</a></dd> <dd><a href="working_with_javascript_in_rails.html">Working with JavaScript in Rails</a></dd> <dd><a href="autoloading_and_reloading_constants.html">Autoloading and Reloading</a></dd> <dd><a href="caching_with_rails.html">Caching with Rails: An Overview</a></dd> <dd><a href="api_app.html">Using Rails for API-only Applications</a></dd> <dd><a href="tuning_performance_for_deployment.html">Tuning Performance for Deployment</a></dd> </div> <div class="guides-section"> <dt>Advanced Active Record</dt> <dd><a href="active_record_multiple_databases.html">Multiple Databases</a></dd> <dd><a href="active_record_composite_primary_keys.html">Composite Primary Keys</a></dd> </div> <div class="guides-section"> <dt>Extending Rails</dt> <dd><a href="rails_on_rack.html">Rails on Rack</a></dd> <dd><a href="generators.html">Creating and Customizing Rails Generators &amp; Templates</a></dd> </div> <div class="guides-section"> <dt>Contributing</dt> <dd><a href="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</a></dd> <dd><a href="api_documentation_guidelines.html">API Documentation Guidelines</a></dd> <dd><a href="ruby_on_rails_guides_guidelines.html">Guides Guidelines</a></dd> <dd><a href="development_dependencies_install.html">Installing Rails Core Development Dependencies</a></dd> </div> <div class="guides-section"> <dt>Policies</dt> <dd><a href="maintenance_policy.html">Maintenance Policy</a></dd> </div> <div class="guides-section"> <dt>Release Notes</dt> <dd><a href="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</a></dd> <dd><a href="7_2_release_notes.html">Version 7.2 - August 2024</a></dd> <dd><a href="7_1_release_notes.html">Version 7.1 - October 2023</a></dd> <dd><a href="7_0_release_notes.html">Version 7.0 - December 2021</a></dd> <dd><a href="6_1_release_notes.html">Version 6.1 - December 2020</a></dd> <dd><a href="6_0_release_notes.html">Version 6.0 - August 2019</a></dd> <dd><a href="5_2_release_notes.html">Version 5.2 - April 2018</a></dd> <dd><a href="5_1_release_notes.html">Version 5.1 - April 2017</a></dd> <dd><a href="5_0_release_notes.html">Version 5.0 - June 2016</a></dd> <dd><a href="4_2_release_notes.html">Version 4.2 - December 2014</a></dd> <dd><a href="4_1_release_notes.html">Version 4.1 - April 2014</a></dd> <dd><a href="4_0_release_notes.html">Version 4.0 - June 2013</a></dd> <dd><a href="3_2_release_notes.html">Version 3.2 - January 2012</a></dd> <dd><a href="3_1_release_notes.html">Version 3.1 - August 2011</a></dd> <dd><a href="3_0_release_notes.html">Version 3.0 - August 2010</a></dd> <dd><a href="2_3_release_notes.html">Version 2.3 - March 2009</a></dd> <dd><a href="2_2_release_notes.html">Version 2.2 - November 2008</a></dd> </div> </dl> </div> </li> <li><a class="nav-item" href="contributing_to_ruby_on_rails.html">Contribute</a></li> <li class="guides-index guides-index-small js-only"> <label for="guides-selector"> Navigate to a guide: </label> <select id="guides-selector" class="guides-index-item nav-item"> <option value="index.html">Guides Index</option> <optgroup label="Start Here"> <option value="getting_started.html">Getting Started with Rails</option> </optgroup> <optgroup label="Models"> <option value="active_record_basics.html">Active Record Basics</option> <option value="active_record_migrations.html">Active Record Migrations</option> <option value="active_record_validations.html">Active Record Validations</option> <option value="active_record_callbacks.html">Active Record Callbacks</option> <option value="association_basics.html">Active Record Associations</option> <option value="active_record_querying.html">Active Record Query Interface</option> <option value="active_model_basics.html">Active Model Basics</option> </optgroup> <optgroup label="Views"> <option value="action_view_overview.html">Action View Overview</option> <option value="layouts_and_rendering.html">Layouts and Rendering in Rails</option> <option value="action_view_helpers.html">Action View Helpers</option> <option value="form_helpers.html">Action View Form Helpers</option> </optgroup> <optgroup label="Controllers"> <option value="action_controller_overview.html">Action Controller Overview</option> <option value="routing.html">Rails Routing from the Outside In</option> </optgroup> <optgroup label="Other Components"> <option value="active_support_core_extensions.html">Active Support Core Extensions</option> <option value="action_mailer_basics.html">Action Mailer Basics</option> <option value="action_mailbox_basics.html">Action Mailbox Basics</option> <option value="action_text_overview.html">Action Text Overview</option> <option value="active_job_basics.html">Active Job Basics</option> <option value="active_storage_overview.html">Active Storage Overview</option> <option value="action_cable_overview.html">Action Cable Overview</option> </optgroup> <optgroup label="Digging Deeper"> <option value="i18n.html">Rails Internationalization (I18n) API</option> <option value="testing.html">Testing Rails Applications</option> <option value="security.html">Securing Rails Applications</option> <option value="error_reporting.html">Error Reporting in Rails Applications</option> <option value="debugging_rails_applications.html">Debugging Rails Applications</option> <option value="configuring.html">Configuring Rails Applications</option> <option value="command_line.html">The Rails Command Line</option> <option value="asset_pipeline.html">The Asset Pipeline</option> <option value="working_with_javascript_in_rails.html">Working with JavaScript in Rails</option> <option value="autoloading_and_reloading_constants.html">Autoloading and Reloading</option> <option value="caching_with_rails.html">Caching with Rails: An Overview</option> <option value="api_app.html">Using Rails for API-only Applications</option> <option value="tuning_performance_for_deployment.html">Tuning Performance for Deployment</option> </optgroup> <optgroup label="Advanced Active Record"> <option value="active_record_multiple_databases.html">Multiple Databases</option> <option value="active_record_composite_primary_keys.html">Composite Primary Keys</option> </optgroup> <optgroup label="Extending Rails"> <option value="rails_on_rack.html">Rails on Rack</option> <option value="generators.html">Creating and Customizing Rails Generators &amp; Templates</option> </optgroup> <optgroup label="Contributing"> <option value="contributing_to_ruby_on_rails.html">Contributing to Ruby on Rails</option> <option value="api_documentation_guidelines.html">API Documentation Guidelines</option> <option value="ruby_on_rails_guides_guidelines.html">Guides Guidelines</option> <option value="development_dependencies_install.html">Installing Rails Core Development Dependencies</option> </optgroup> <optgroup label="Policies"> <option value="maintenance_policy.html">Maintenance Policy</option> </optgroup> <optgroup label="Release Notes"> <option value="upgrading_ruby_on_rails.html">Upgrading Ruby on Rails</option> <option value="7_2_release_notes.html">Version 7.2 - August 2024</option> <option value="7_1_release_notes.html">Version 7.1 - October 2023</option> <option value="7_0_release_notes.html">Version 7.0 - December 2021</option> <option value="6_1_release_notes.html">Version 6.1 - December 2020</option> <option value="6_0_release_notes.html">Version 6.0 - August 2019</option> <option value="5_2_release_notes.html">Version 5.2 - April 2018</option> <option value="5_1_release_notes.html">Version 5.1 - April 2017</option> <option value="5_0_release_notes.html">Version 5.0 - June 2016</option> <option value="4_2_release_notes.html">Version 4.2 - December 2014</option> <option value="4_1_release_notes.html">Version 4.1 - April 2014</option> <option value="4_0_release_notes.html">Version 4.0 - June 2013</option> <option value="3_2_release_notes.html">Version 3.2 - January 2012</option> <option value="3_1_release_notes.html">Version 3.1 - August 2011</option> <option value="3_0_release_notes.html">Version 3.0 - August 2010</option> <option value="2_3_release_notes.html">Version 2.3 - March 2009</option> <option value="2_2_release_notes.html">Version 2.2 - November 2008</option> </optgroup> </select> </li> </ul> </nav> </div> </header> <hr class="hide" /> <main id="main"> <article> <header id="feature"> <div class="wrapper"> <h1>Layouts and Rendering in Rails</h1><p>This guide covers the basic layout features of Action Controller and Action View.</p><p>After reading this guide, you will know:</p> <ul> <li>How to use the various rendering methods built into Rails.</li> <li>How to create layouts with multiple content sections.</li> <li>How to use partials to DRY up your views.</li> <li>How to use nested layouts (sub-templates).</li> </ul> <nav id="column-side" aria-label="Chapter" class="guide-index" data-turbo="false"> <a id="chapter-nav-skip-link" href="#article-body" class="skip-link"> Skip to article body </a> <h2 class="chapter"> <picture aria-hidden="true"> <!-- Using the `source` HTML tag to set the dark theme image --> <source srcset="images/icon_book-close-bookmark-1-wht.svg" media="(prefers-color-scheme: dark)" /> <img src="images/icon_book-close-bookmark-1.svg" alt="Chapter Icon" /> </picture> Chapters </h2> <ol class="chapters"> <li><a href="#overview-how-the-pieces-fit-together">Overview: How the Pieces Fit Together</a></li> <li><a href="#creating-responses">Creating Responses</a> <ul> <li><a href="#rendering-by-default-convention-over-configuration-in-action">Rendering by Default: Convention Over Configuration in Action</a></li> <li><a href="#using-render">Using <code>render</code></a></li> <li><a href="#using-redirect-to">Using <code>redirect_to</code></a></li> <li><a href="#using-head-to-build-header-only-responses">Using <code>head</code> to Build Header-Only Responses</a></li> </ul></li> <li><a href="#structuring-layouts">Structuring Layouts</a> <ul> <li><a href="#asset-tag-helpers">Asset Tag Helpers</a></li> <li><a href="#understanding-yield">Understanding <code>yield</code></a></li> <li><a href="#using-the-content-for-method">Using the <code>content_for</code> Method</a></li> <li><a href="#using-partials">Using Partials</a></li> <li><a href="#using-nested-layouts">Using Nested Layouts</a></li> </ul></li> </ol> </nav> </div> </header> <div class="wrapper"> <div id="column-main"> <section id="article-body"> <h2 id="overview-how-the-pieces-fit-together"><a class="anchorlink" href="#overview-how-the-pieces-fit-together" data-turbo="false"><span>1</span> Overview: How the Pieces Fit Together</a></h2><p>This guide focuses on the interaction between Controller and View in the Model-View-Controller triangle. As you know, the Controller is responsible for orchestrating the whole process of handling a request in Rails, though it normally hands off any heavy code to the Model. But then, when it's time to send a response back to the user, the Controller hands things off to the View. It's that handoff that is the subject of this guide.</p><p>In broad strokes, this involves deciding what should be sent as the response and calling an appropriate method to create that response. If the response is a full-blown view, Rails also does some extra work to wrap the view in a layout and possibly to pull in partial views. You'll see all of those paths later in this guide.</p><h2 id="creating-responses"><a class="anchorlink" href="#creating-responses" data-turbo="false"><span>2</span> Creating Responses</a></h2><p>From the controller's point of view, there are three ways to create an HTTP response:</p> <ul> <li>Call <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionController/Rendering.html#method-i-render"><code>render</code></a> to create a full response to send back to the browser</li> <li>Call <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionController/Redirecting.html#method-i-redirect_to"><code>redirect_to</code></a> to send an HTTP redirect status code to the browser</li> <li>Call <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionController/Head.html#method-i-head"><code>head</code></a> to create a response consisting solely of HTTP headers to send back to the browser</li> </ul> <h3 id="rendering-by-default-convention-over-configuration-in-action"><a class="anchorlink" href="#rendering-by-default-convention-over-configuration-in-action" data-turbo="false"><span>2.1</span> Rendering by Default: Convention Over Configuration in Action</a></h3><p>You've heard that Rails promotes "convention over configuration". Default rendering is an excellent example of this. By default, controllers in Rails automatically render views with names that correspond to valid routes. For example, if you have this code in your <code>BooksController</code> class:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">BooksController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class BooksController < ApplicationController end ">Copy</button> </div> <p>And the following in your routes file:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">resources</span> <span class="ss">:books</span> </code></pre> <button class="clipboard-button" data-clipboard-text="resources :books ">Copy</button> </div> <p>And you have a view file <code>app/views/books/index.html.erb</code>:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;h1&gt;</span>Books are coming soon!<span class="nt">&lt;/h1&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<h1>Books are coming soon!</h1> ">Copy</button> </div> <p>Rails will automatically render <code>app/views/books/index.html.erb</code> when you navigate to <code>/books</code> and you will see "Books are coming soon!" on your screen.</p><p>However, a coming soon screen is only minimally useful, so you will soon create your <code>Book</code> model and add the index action to <code>BooksController</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">BooksController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">def</span> <span class="nf">index</span> <span class="vi">@books</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">all</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class BooksController < ApplicationController def index @books = Book.all end end ">Copy</button> </div> <p>Note that we don't have explicit render at the end of the index action in accordance with "convention over configuration" principle. The rule is that if you do not explicitly render something at the end of a controller action, Rails will automatically look for the <code>action_name.html.erb</code> template in the controller's view path and render it. So in this case, Rails will render the <code>app/views/books/index.html.erb</code> file.</p><p>If we want to display the properties of all the books in our view, we can do so with an ERB template like this:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;h1&gt;</span>Listing Books<span class="nt">&lt;/h1&gt;</span> <span class="nt">&lt;table&gt;</span> <span class="nt">&lt;thead&gt;</span> <span class="nt">&lt;tr&gt;</span> <span class="nt">&lt;th&gt;</span>Title<span class="nt">&lt;/th&gt;</span> <span class="nt">&lt;th&gt;</span>Content<span class="nt">&lt;/th&gt;</span> <span class="nt">&lt;th</span> <span class="na">colspan=</span><span class="s">"3"</span><span class="nt">&gt;&lt;/th&gt;</span> <span class="nt">&lt;/tr&gt;</span> <span class="nt">&lt;/thead&gt;</span> <span class="nt">&lt;tbody&gt;</span> <span class="cp">&lt;%</span> <span class="vi">@books</span><span class="p">.</span><span class="nf">each</span> <span class="k">do</span> <span class="o">|</span><span class="n">book</span><span class="o">|</span> <span class="cp">%&gt;</span> <span class="nt">&lt;tr&gt;</span> <span class="nt">&lt;td&gt;</span><span class="cp">&lt;%=</span> <span class="n">book</span><span class="p">.</span><span class="nf">title</span> <span class="cp">%&gt;</span><span class="nt">&lt;/td&gt;</span> <span class="nt">&lt;td&gt;</span><span class="cp">&lt;%=</span> <span class="n">book</span><span class="p">.</span><span class="nf">content</span> <span class="cp">%&gt;</span><span class="nt">&lt;/td&gt;</span> <span class="nt">&lt;td&gt;</span><span class="cp">&lt;%=</span> <span class="n">link_to</span> <span class="s2">"Show"</span><span class="p">,</span> <span class="n">book</span> <span class="cp">%&gt;</span><span class="nt">&lt;/td&gt;</span> <span class="nt">&lt;td&gt;</span><span class="cp">&lt;%=</span> <span class="n">link_to</span> <span class="s2">"Edit"</span><span class="p">,</span> <span class="n">edit_book_path</span><span class="p">(</span><span class="n">book</span><span class="p">)</span> <span class="cp">%&gt;</span><span class="nt">&lt;/td&gt;</span> <span class="nt">&lt;td&gt;</span><span class="cp">&lt;%=</span> <span class="n">link_to</span> <span class="s2">"Destroy"</span><span class="p">,</span> <span class="n">book</span><span class="p">,</span> <span class="ss">data: </span><span class="p">{</span> <span class="ss">turbo_method: :delete</span><span class="p">,</span> <span class="ss">turbo_confirm: </span><span class="s2">"Are you sure?"</span> <span class="p">}</span> <span class="cp">%&gt;</span><span class="nt">&lt;/td&gt;</span> <span class="nt">&lt;/tr&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> <span class="nt">&lt;/tbody&gt;</span> <span class="nt">&lt;/table&gt;</span> <span class="nt">&lt;br&gt;</span> <span class="cp">&lt;%=</span> <span class="n">link_to</span> <span class="s2">"New book"</span><span class="p">,</span> <span class="n">new_book_path</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<h1>Listing Books</h1> <table> <thead> <tr> <th>Title</th> <th>Content</th> <th colspan=&quot;3&quot;></th> </tr> </thead> <tbody> <% @books.each do |book| %> <tr> <td><%= book.title %></td> <td><%= book.content %></td> <td><%= link_to &quot;Show&quot;, book %></td> <td><%= link_to &quot;Edit&quot;, edit_book_path(book) %></td> <td><%= link_to &quot;Destroy&quot;, book, data: { turbo_method: :delete, turbo_confirm: &quot;Are you sure?&quot; } %></td> </tr> <% end %> </tbody> </table> <br> <%= link_to &quot;New book&quot;, new_book_path %> ">Copy</button> </div> <div class="interstitial note"><p>The actual rendering is done by nested classes of the module <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Template/Handlers.html"><code>ActionView::Template::Handlers</code></a>. This guide does not dig into that process, but it's important to know that the file extension on your view controls the choice of template handler.</p></div><h3 id="using-render"><a class="anchorlink" href="#using-render" data-turbo="false"><span>2.2</span> Using <code>render</code></a></h3><p>In most cases, the controller's <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionController/Rendering.html#method-i-render"><code>render</code></a> method does the heavy lifting of rendering your application's content for use by a browser. There are a variety of ways to customize the behavior of <code>render</code>. You can render the default view for a Rails template, or a specific template, or a file, or inline code, or nothing at all. You can render text, JSON, or XML. You can specify the content type or HTTP status of the rendered response as well.</p><div class="interstitial info"><p>If you want to see the exact results of a call to <code>render</code> without needing to inspect it in a browser, you can call <code>render_to_string</code>. This method takes exactly the same options as <code>render</code>, but it returns a string instead of sending a response back to the browser.</p></div><h4 id="rendering-an-action-s-view"><a class="anchorlink" href="#rendering-an-action-s-view" data-turbo="false"><span>2.2.1</span> Rendering an Action's View</a></h4><p>If you want to render the view that corresponds to a different template within the same controller, you can use <code>render</code> with the name of the view:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">update</span> <span class="vi">@book</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="k">if</span> <span class="vi">@book</span><span class="p">.</span><span class="nf">update</span><span class="p">(</span><span class="n">book_params</span><span class="p">)</span> <span class="n">redirect_to</span><span class="p">(</span><span class="vi">@book</span><span class="p">)</span> <span class="k">else</span> <span class="n">render</span> <span class="s2">"edit"</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def update @book = Book.find(params[:id]) if @book.update(book_params) redirect_to(@book) else render &quot;edit&quot; end end ">Copy</button> </div> <p>If the call to <code>update</code> fails, calling the <code>update</code> action in this controller will render the <code>edit.html.erb</code> template belonging to the same controller.</p><p>If you prefer, you can use a symbol instead of a string to specify the action to render:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">update</span> <span class="vi">@book</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="k">if</span> <span class="vi">@book</span><span class="p">.</span><span class="nf">update</span><span class="p">(</span><span class="n">book_params</span><span class="p">)</span> <span class="n">redirect_to</span><span class="p">(</span><span class="vi">@book</span><span class="p">)</span> <span class="k">else</span> <span class="n">render</span> <span class="ss">:edit</span><span class="p">,</span> <span class="ss">status: :unprocessable_entity</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def update @book = Book.find(params[:id]) if @book.update(book_params) redirect_to(@book) else render :edit, status: :unprocessable_entity end end ">Copy</button> </div> <h4 id="rendering-an-action-s-template-from-another-controller"><a class="anchorlink" href="#rendering-an-action-s-template-from-another-controller" data-turbo="false"><span>2.2.2</span> Rendering an Action's Template from Another Controller</a></h4><p>What if you want to render a template from an entirely different controller from the one that contains the action code? You can also do that with <code>render</code>, which accepts the full path (relative to <code>app/views</code>) of the template to render. For example, if you're running code in an <code>AdminProductsController</code> that lives in <code>app/controllers/admin</code>, you can render the results of an action to a template in <code>app/views/products</code> this way:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="s2">"products/show"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render &quot;products/show&quot; ">Copy</button> </div> <p>Rails knows that this view belongs to a different controller because of the embedded slash character in the string. If you want to be explicit, you can use the <code>:template</code> option (which was required on Rails 2.2 and earlier):</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">template: </span><span class="s2">"products/show"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render template: &quot;products/show&quot; ">Copy</button> </div> <h4 id="wrapping-it-up"><a class="anchorlink" href="#wrapping-it-up" data-turbo="false"><span>2.2.3</span> Wrapping it up</a></h4><p>The above two ways of rendering (rendering the template of another action in the same controller, and rendering the template of another action in a different controller) are actually variants of the same operation.</p><p>In fact, in the <code>BooksController</code> class, inside of the update action where we want to render the edit template if the book does not update successfully, all of the following render calls would all render the <code>edit.html.erb</code> template in the <code>views/books</code> directory:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">:edit</span> <span class="n">render</span> <span class="ss">action: :edit</span> <span class="n">render</span> <span class="s2">"edit"</span> <span class="n">render</span> <span class="ss">action: </span><span class="s2">"edit"</span> <span class="n">render</span> <span class="s2">"books/edit"</span> <span class="n">render</span> <span class="ss">template: </span><span class="s2">"books/edit"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render :edit render action: :edit render &quot;edit&quot; render action: &quot;edit&quot; render &quot;books/edit&quot; render template: &quot;books/edit&quot; ">Copy</button> </div> <p>Which one you use is really a matter of style and convention, but the rule of thumb is to use the simplest one that makes sense for the code you are writing.</p><h4 id="using-render-with-inline"><a class="anchorlink" href="#using-render-with-inline" data-turbo="false"><span>2.2.4</span> Using <code>render</code> with <code>:inline</code></a></h4><p>The <code>render</code> method can do without a view completely, if you're willing to use the <code>:inline</code> option to supply ERB as part of the method call. This is perfectly valid:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">inline: </span><span class="s2">"&lt;% products.each do |p| %&gt;&lt;p&gt;&lt;%= p.name %&gt;&lt;/p&gt;&lt;% end %&gt;"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render inline: &quot;<% products.each do |p| %><p><%= p.name %></p><% end %>&quot; ">Copy</button> </div> <div class="interstitial warning"><p>There is seldom any good reason to use this option. Mixing ERB into your controllers defeats the MVC orientation of Rails and will make it harder for other developers to follow the logic of your project. Use a separate erb view instead.</p></div><p>By default, inline rendering uses ERB. You can force it to use Builder instead with the <code>:type</code> option:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">inline: </span><span class="s2">"xml.p {'Horrid coding practice!'}"</span><span class="p">,</span> <span class="ss">type: :builder</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render inline: &quot;xml.p {'Horrid coding practice!'}&quot;, type: :builder ">Copy</button> </div> <h4 id="rendering-text"><a class="anchorlink" href="#rendering-text" data-turbo="false"><span>2.2.5</span> Rendering Text</a></h4><p>You can send plain text - with no markup at all - back to the browser by using the <code>:plain</code> option to <code>render</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">plain: </span><span class="s2">"OK"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render plain: &quot;OK&quot; ">Copy</button> </div> <div class="interstitial info"><p>Rendering pure text is most useful when you're responding to Ajax or web service requests that are expecting something other than proper HTML.</p></div><div class="interstitial note"><p>By default, if you use the <code>:plain</code> option, the text is rendered without using the current layout. If you want Rails to put the text into the current layout, you need to add the <code>layout: true</code> option and use the <code>.text.erb</code> extension for the layout file.</p></div><h4 id="rendering-html"><a class="anchorlink" href="#rendering-html" data-turbo="false"><span>2.2.6</span> Rendering HTML</a></h4><p>You can send an HTML string back to the browser by using the <code>:html</code> option to <code>render</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">html: </span><span class="n">helpers</span><span class="p">.</span><span class="nf">tag</span><span class="p">.</span><span class="nf">strong</span><span class="p">(</span><span class="s2">"Not Found"</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render html: helpers.tag.strong(&quot;Not Found&quot;) ">Copy</button> </div> <div class="interstitial info"><p>This is useful when you're rendering a small snippet of HTML code. However, you might want to consider moving it to a template file if the markup is complex.</p></div><div class="interstitial note"><p>When using <code>html:</code> option, HTML entities will be escaped if the string is not composed with <code>html_safe</code>-aware APIs.</p></div><h4 id="rendering-json"><a class="anchorlink" href="#rendering-json" data-turbo="false"><span>2.2.7</span> Rendering JSON</a></h4><p>JSON is a JavaScript data format used by many Ajax libraries. Rails has built-in support for converting objects to JSON and rendering that JSON back to the browser:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">json: </span><span class="vi">@product</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render json: @product ">Copy</button> </div> <div class="interstitial info"><p>You don't need to call <code>to_json</code> on the object that you want to render. If you use the <code>:json</code> option, <code>render</code> will automatically call <code>to_json</code> for you.</p></div><h4 id="rendering-xml"><a class="anchorlink" href="#rendering-xml" data-turbo="false"><span>2.2.8</span> Rendering XML</a></h4><p>Rails also has built-in support for converting objects to XML and rendering that XML back to the caller:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">xml: </span><span class="vi">@product</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render xml: @product ">Copy</button> </div> <div class="interstitial info"><p>You don't need to call <code>to_xml</code> on the object that you want to render. If you use the <code>:xml</code> option, <code>render</code> will automatically call <code>to_xml</code> for you.</p></div><h4 id="rendering-vanilla-javascript"><a class="anchorlink" href="#rendering-vanilla-javascript" data-turbo="false"><span>2.2.9</span> Rendering Vanilla JavaScript</a></h4><p>Rails can render vanilla JavaScript:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">js: </span><span class="s2">"alert('Hello Rails');"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render js: &quot;alert('Hello Rails');&quot; ">Copy</button> </div> <p>This will send the supplied string to the browser with a MIME type of <code>text/javascript</code>.</p><h4 id="rendering-raw-body"><a class="anchorlink" href="#rendering-raw-body" data-turbo="false"><span>2.2.10</span> Rendering Raw Body</a></h4><p>You can send a raw content back to the browser, without setting any content type, by using the <code>:body</code> option to <code>render</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">body: </span><span class="s2">"raw"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render body: &quot;raw&quot; ">Copy</button> </div> <div class="interstitial info"><p>This option should be used only if you don't care about the content type of the response. Using <code>:plain</code> or <code>:html</code> might be more appropriate most of the time.</p></div><div class="interstitial note"><p>Unless overridden, your response returned from this render option will be <code>text/plain</code>, as that is the default content type of Action Dispatch response.</p></div><h4 id="rendering-raw-file"><a class="anchorlink" href="#rendering-raw-file" data-turbo="false"><span>2.2.11</span> Rendering Raw File</a></h4><p>Rails can render a raw file from an absolute path. This is useful for conditionally rendering static files like error pages.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">file: </span><span class="s2">"</span><span class="si">#{</span><span class="no">Rails</span><span class="p">.</span><span class="nf">root</span><span class="si">}</span><span class="s2">/public/404.html"</span><span class="p">,</span> <span class="ss">layout: </span><span class="kp">false</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render file: &quot;#{Rails.root}/public/404.html&quot;, layout: false ">Copy</button> </div> <p>This renders the raw file (it doesn't support ERB or other handlers). By default it is rendered within the current layout.</p><div class="interstitial warning"><p>Using the <code>:file</code> option in combination with users input can lead to security problems since an attacker could use this action to access security sensitive files in your file system.</p></div><div class="interstitial info"><p><code>send_file</code> is often a faster and better option if a layout isn't required.</p></div><h4 id="rendering-objects"><a class="anchorlink" href="#rendering-objects" data-turbo="false"><span>2.2.12</span> Rendering Objects</a></h4><p>Rails can render objects responding to <code>#render_in</code>. The format can be controlled by defining <code>#format</code> on the object.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">Greeting</span> <span class="k">def</span> <span class="nf">render_in</span><span class="p">(</span><span class="n">view_context</span><span class="p">)</span> <span class="n">view_context</span><span class="p">.</span><span class="nf">render</span> <span class="ss">html: </span><span class="s2">"Hello, World"</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">format</span> <span class="ss">:html</span> <span class="k">end</span> <span class="k">end</span> <span class="n">render</span> <span class="no">Greeting</span><span class="p">.</span><span class="nf">new</span> <span class="c1"># =&gt; "Hello World"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Greeting def render_in(view_context) view_context.render html: &quot;Hello, World&quot; end def format :html end end render Greeting.new # => &quot;Hello World&quot; ">Copy</button> </div> <p>This calls <code>render_in</code> on the provided object with the current view context. You can also provide the object by using the <code>:renderable</code> option to <code>render</code>:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">renderable: </span><span class="no">Greeting</span><span class="p">.</span><span class="nf">new</span> <span class="c1"># =&gt; "Hello World"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render renderable: Greeting.new # => &quot;Hello World&quot; ">Copy</button> </div> <h4 id="options-for-render"><a class="anchorlink" href="#options-for-render" data-turbo="false"><span>2.2.13</span> Options for <code>render</code></a></h4><p>Calls to the <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionController/Rendering.html#method-i-render"><code>render</code></a> method generally accept six options:</p> <ul> <li><code>:content_type</code></li> <li><code>:layout</code></li> <li><code>:location</code></li> <li><code>:status</code></li> <li><code>:formats</code></li> <li><code>:variants</code></li> </ul> <h5 id="the-content-type-option"><a class="anchorlink" href="#the-content-type-option" data-turbo="false"><span>2.2.13.1</span> The <code>:content_type</code> Option</a></h5><p>By default, Rails will serve the results of a rendering operation with the MIME content-type of <code>text/html</code> (or <code>application/json</code> if you use the <code>:json</code> option, or <code>application/xml</code> for the <code>:xml</code> option.). There are times when you might like to change this, and you can do so by setting the <code>:content_type</code> option:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">template: </span><span class="s2">"feed"</span><span class="p">,</span> <span class="ss">content_type: </span><span class="s2">"application/rss"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render template: &quot;feed&quot;, content_type: &quot;application/rss&quot; ">Copy</button> </div> <h5 id="the-layout-option"><a class="anchorlink" href="#the-layout-option" data-turbo="false"><span>2.2.13.2</span> The <code>:layout</code> Option</a></h5><p>With most of the options to <code>render</code>, the rendered content is displayed as part of the current layout. You'll learn more about layouts and how to use them later in this guide.</p><p>You can use the <code>:layout</code> option to tell Rails to use a specific file as the layout for the current action:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">layout: </span><span class="s2">"special_layout"</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render layout: &quot;special_layout&quot; ">Copy</button> </div> <p>You can also tell Rails to render with no layout at all:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">layout: </span><span class="kp">false</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render layout: false ">Copy</button> </div> <h5 id="the-location-option"><a class="anchorlink" href="#the-location-option" data-turbo="false"><span>2.2.13.3</span> The <code>:location</code> Option</a></h5><p>You can use the <code>:location</code> option to set the HTTP <code>Location</code> header:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">xml: </span><span class="n">photo</span><span class="p">,</span> <span class="ss">location: </span><span class="n">photo_url</span><span class="p">(</span><span class="n">photo</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render xml: photo, location: photo_url(photo) ">Copy</button> </div> <h5 id="the-status-option"><a class="anchorlink" href="#the-status-option" data-turbo="false"><span>2.2.13.4</span> The <code>:status</code> Option</a></h5><p>Rails will automatically generate a response with the correct HTTP status code (in most cases, this is <code>200 OK</code>). You can use the <code>:status</code> option to change this:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">status: </span><span class="mi">500</span> <span class="n">render</span> <span class="ss">status: :forbidden</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render status: 500 render status: :forbidden ">Copy</button> </div> <p>Rails understands both numeric status codes and the corresponding symbols shown below.</p> <div class="table-wrapper"><table><thead> <tr> <th>Response Class</th> <th>HTTP Status Code</th> <th>Symbol</th> </tr> </thead><tbody> <tr> <td><strong>Informational</strong></td> <td>100</td> <td>:continue</td> </tr> <tr> <td></td> <td>101</td> <td>:switching_protocols</td> </tr> <tr> <td></td> <td>102</td> <td>:processing</td> </tr> <tr> <td><strong>Success</strong></td> <td>200</td> <td>:ok</td> </tr> <tr> <td></td> <td>201</td> <td>:created</td> </tr> <tr> <td></td> <td>202</td> <td>:accepted</td> </tr> <tr> <td></td> <td>203</td> <td>:non_authoritative_information</td> </tr> <tr> <td></td> <td>204</td> <td>:no_content</td> </tr> <tr> <td></td> <td>205</td> <td>:reset_content</td> </tr> <tr> <td></td> <td>206</td> <td>:partial_content</td> </tr> <tr> <td></td> <td>207</td> <td>:multi_status</td> </tr> <tr> <td></td> <td>208</td> <td>:already_reported</td> </tr> <tr> <td></td> <td>226</td> <td>:im_used</td> </tr> <tr> <td><strong>Redirection</strong></td> <td>300</td> <td>:multiple_choices</td> </tr> <tr> <td></td> <td>301</td> <td>:moved_permanently</td> </tr> <tr> <td></td> <td>302</td> <td>:found</td> </tr> <tr> <td></td> <td>303</td> <td>:see_other</td> </tr> <tr> <td></td> <td>304</td> <td>:not_modified</td> </tr> <tr> <td></td> <td>305</td> <td>:use_proxy</td> </tr> <tr> <td></td> <td>307</td> <td>:temporary_redirect</td> </tr> <tr> <td></td> <td>308</td> <td>:permanent_redirect</td> </tr> <tr> <td><strong>Client Error</strong></td> <td>400</td> <td>:bad_request</td> </tr> <tr> <td></td> <td>401</td> <td>:unauthorized</td> </tr> <tr> <td></td> <td>402</td> <td>:payment_required</td> </tr> <tr> <td></td> <td>403</td> <td>:forbidden</td> </tr> <tr> <td></td> <td>404</td> <td>:not_found</td> </tr> <tr> <td></td> <td>405</td> <td>:method_not_allowed</td> </tr> <tr> <td></td> <td>406</td> <td>:not_acceptable</td> </tr> <tr> <td></td> <td>407</td> <td>:proxy_authentication_required</td> </tr> <tr> <td></td> <td>408</td> <td>:request_timeout</td> </tr> <tr> <td></td> <td>409</td> <td>:conflict</td> </tr> <tr> <td></td> <td>410</td> <td>:gone</td> </tr> <tr> <td></td> <td>411</td> <td>:length_required</td> </tr> <tr> <td></td> <td>412</td> <td>:precondition_failed</td> </tr> <tr> <td></td> <td>413</td> <td>:payload_too_large</td> </tr> <tr> <td></td> <td>414</td> <td>:uri_too_long</td> </tr> <tr> <td></td> <td>415</td> <td>:unsupported_media_type</td> </tr> <tr> <td></td> <td>416</td> <td>:range_not_satisfiable</td> </tr> <tr> <td></td> <td>417</td> <td>:expectation_failed</td> </tr> <tr> <td></td> <td>421</td> <td>:misdirected_request</td> </tr> <tr> <td></td> <td>422</td> <td>:unprocessable_entity</td> </tr> <tr> <td></td> <td>423</td> <td>:locked</td> </tr> <tr> <td></td> <td>424</td> <td>:failed_dependency</td> </tr> <tr> <td></td> <td>426</td> <td>:upgrade_required</td> </tr> <tr> <td></td> <td>428</td> <td>:precondition_required</td> </tr> <tr> <td></td> <td>429</td> <td>:too_many_requests</td> </tr> <tr> <td></td> <td>431</td> <td>:request_header_fields_too_large</td> </tr> <tr> <td></td> <td>451</td> <td>:unavailable_for_legal_reasons</td> </tr> <tr> <td><strong>Server Error</strong></td> <td>500</td> <td>:internal_server_error</td> </tr> <tr> <td></td> <td>501</td> <td>:not_implemented</td> </tr> <tr> <td></td> <td>502</td> <td>:bad_gateway</td> </tr> <tr> <td></td> <td>503</td> <td>:service_unavailable</td> </tr> <tr> <td></td> <td>504</td> <td>:gateway_timeout</td> </tr> <tr> <td></td> <td>505</td> <td>:http_version_not_supported</td> </tr> <tr> <td></td> <td>506</td> <td>:variant_also_negotiates</td> </tr> <tr> <td></td> <td>507</td> <td>:insufficient_storage</td> </tr> <tr> <td></td> <td>508</td> <td>:loop_detected</td> </tr> <tr> <td></td> <td>510</td> <td>:not_extended</td> </tr> <tr> <td></td> <td>511</td> <td>:network_authentication_required</td> </tr> </tbody></table></div> <div class="interstitial note"><p>If you try to render content along with a non-content status code (100-199, 204, 205, or 304), it will be dropped from the response.</p></div><h5 id="the-formats-option"><a class="anchorlink" href="#the-formats-option" data-turbo="false"><span>2.2.13.5</span> The <code>:formats</code> Option</a></h5><p>Rails uses the format specified in the request (or <code>:html</code> by default). You can change this passing the <code>:formats</code> option with a symbol or an array:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">render</span> <span class="ss">formats: :xml</span> <span class="n">render</span> <span class="ss">formats: </span><span class="p">[</span><span class="ss">:json</span><span class="p">,</span> <span class="ss">:xml</span><span class="p">]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="render formats: :xml render formats: [:json, :xml] ">Copy</button> </div> <p>If a template with the specified format does not exist an <code>ActionView::MissingTemplate</code> error is raised.</p><h5 id="the-variants-option"><a class="anchorlink" href="#the-variants-option" data-turbo="false"><span>2.2.13.6</span> The <code>:variants</code> Option</a></h5><p>This tells Rails to look for template variations of the same format. You can specify a list of variants by passing the <code>:variants</code> option with a symbol or an array.</p><p>An example of use would be this.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># called in HomeController#index</span> <span class="n">render</span> <span class="ss">variants: </span><span class="p">[</span><span class="ss">:mobile</span><span class="p">,</span> <span class="ss">:desktop</span><span class="p">]</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# called in HomeController#index render variants: [:mobile, :desktop] ">Copy</button> </div> <p>With this set of variants Rails will look for the following set of templates and use the first that exists.</p> <ul> <li><code>app/views/home/index.html+mobile.erb</code></li> <li><code>app/views/home/index.html+desktop.erb</code></li> <li><code>app/views/home/index.html.erb</code></li> </ul> <p>If a template with the specified format does not exist an <code>ActionView::MissingTemplate</code> error is raised.</p><p>Instead of setting the variant on the render call you may also set it on the request object in your controller action.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">index</span> <span class="n">request</span><span class="p">.</span><span class="nf">variant</span> <span class="o">=</span> <span class="n">determine_variant</span> <span class="k">end</span> <span class="kp">private</span> <span class="k">def</span> <span class="nf">determine_variant</span> <span class="n">variant</span> <span class="o">=</span> <span class="kp">nil</span> <span class="c1"># some code to determine the variant(s) to use</span> <span class="n">variant</span> <span class="o">=</span> <span class="ss">:mobile</span> <span class="k">if</span> <span class="n">session</span><span class="p">[</span><span class="ss">:use_mobile</span><span class="p">]</span> <span class="n">variant</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def index request.variant = determine_variant end private def determine_variant variant = nil # some code to determine the variant(s) to use variant = :mobile if session[:use_mobile] variant end ">Copy</button> </div> <h4 id="finding-layouts"><a class="anchorlink" href="#finding-layouts" data-turbo="false"><span>2.2.14</span> Finding Layouts</a></h4><p>To find the current layout, Rails first looks for a file in <code>app/views/layouts</code> with the same base name as the controller. For example, rendering actions from the <code>PhotosController</code> class will use <code>app/views/layouts/photos.html.erb</code> (or <code>app/views/layouts/photos.builder</code>). If there is no such controller-specific layout, Rails will use <code>app/views/layouts/application.html.erb</code> or <code>app/views/layouts/application.builder</code>. If there is no <code>.erb</code> layout, Rails will use a <code>.builder</code> layout if one exists. Rails also provides several ways to more precisely assign specific layouts to individual controllers and actions.</p><h5 id="specifying-layouts-for-controllers"><a class="anchorlink" href="#specifying-layouts-for-controllers" data-turbo="false"><span>2.2.14.1</span> Specifying Layouts for Controllers</a></h5><p>You can override the default layout conventions in your controllers by using the <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Layouts/ClassMethods.html#method-i-layout"><code>layout</code></a> declaration. For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ProductsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="n">layout</span> <span class="s2">"inventory"</span> <span class="c1">#...</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ProductsController < ApplicationController layout &quot;inventory&quot; #... end ">Copy</button> </div> <p>With this declaration, all of the views rendered by the <code>ProductsController</code> will use <code>app/views/layouts/inventory.html.erb</code> as their layout.</p><p>To assign a specific layout for the entire application, use a <code>layout</code> declaration in your <code>ApplicationController</code> class:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ApplicationController</span> <span class="o">&lt;</span> <span class="no">ActionController</span><span class="o">::</span><span class="no">Base</span> <span class="n">layout</span> <span class="s2">"main"</span> <span class="c1">#...</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ApplicationController < ActionController::Base layout &quot;main&quot; #... end ">Copy</button> </div> <p>With this declaration, all of the views in the entire application will use <code>app/views/layouts/main.html.erb</code> for their layout.</p><h5 id="choosing-layouts-at-runtime"><a class="anchorlink" href="#choosing-layouts-at-runtime" data-turbo="false"><span>2.2.14.2</span> Choosing Layouts at Runtime</a></h5><p>You can use a symbol to defer the choice of layout until a request is processed:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ProductsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="n">layout</span> <span class="ss">:products_layout</span> <span class="k">def</span> <span class="nf">show</span> <span class="vi">@product</span> <span class="o">=</span> <span class="no">Product</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="k">end</span> <span class="kp">private</span> <span class="k">def</span> <span class="nf">products_layout</span> <span class="vi">@current_user</span><span class="p">.</span><span class="nf">special?</span> <span class="p">?</span> <span class="s2">"special"</span> <span class="p">:</span> <span class="s2">"products"</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ProductsController < ApplicationController layout :products_layout def show @product = Product.find(params[:id]) end private def products_layout @current_user.special? ? &quot;special&quot; : &quot;products&quot; end end ">Copy</button> </div> <p>Now, if the current user is a special user, they'll get a special layout when viewing a product.</p><p>You can even use an inline method, such as a Proc, to determine the layout. For example, if you pass a Proc object, the block you give the Proc will be given the <code>controller</code> instance, so the layout can be determined based on the current request:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ProductsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="n">layout</span> <span class="no">Proc</span><span class="p">.</span><span class="nf">new</span> <span class="p">{</span> <span class="o">|</span><span class="n">controller</span><span class="o">|</span> <span class="n">controller</span><span class="p">.</span><span class="nf">request</span><span class="p">.</span><span class="nf">xhr?</span> <span class="p">?</span> <span class="s2">"popup"</span> <span class="p">:</span> <span class="s2">"application"</span> <span class="p">}</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ProductsController < ApplicationController layout Proc.new { |controller| controller.request.xhr? ? &quot;popup&quot; : &quot;application&quot; } end ">Copy</button> </div> <h5 id="conditional-layouts"><a class="anchorlink" href="#conditional-layouts" data-turbo="false"><span>2.2.14.3</span> Conditional Layouts</a></h5><p>Layouts specified at the controller level support the <code>:only</code> and <code>:except</code> options. These options take either a method name, or an array of method names, corresponding to method names within the controller:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ProductsController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="n">layout</span> <span class="s2">"product"</span><span class="p">,</span> <span class="ss">except: </span><span class="p">[</span><span class="ss">:index</span><span class="p">,</span> <span class="ss">:rss</span><span class="p">]</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ProductsController < ApplicationController layout &quot;product&quot;, except: [:index, :rss] end ">Copy</button> </div> <p>With this declaration, the <code>product</code> layout would be used for everything but the <code>rss</code> and <code>index</code> methods.</p><h5 id="layout-inheritance"><a class="anchorlink" href="#layout-inheritance" data-turbo="false"><span>2.2.14.4</span> Layout Inheritance</a></h5><p>Layout declarations cascade downward in the hierarchy, and more specific layout declarations always override more general ones. For example:</p> <ul> <li><p><code>application_controller.rb</code></p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ApplicationController</span> <span class="o">&lt;</span> <span class="no">ActionController</span><span class="o">::</span><span class="no">Base</span> <span class="n">layout</span> <span class="s2">"main"</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ApplicationController < ActionController::Base layout &quot;main&quot; end ">Copy</button> </div></li> <li><p><code>articles_controller.rb</code></p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">ArticlesController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ArticlesController < ApplicationController end ">Copy</button> </div></li> <li><p><code>special_articles_controller.rb</code></p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">SpecialArticlesController</span> <span class="o">&lt;</span> <span class="no">ArticlesController</span> <span class="n">layout</span> <span class="s2">"special"</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class SpecialArticlesController < ArticlesController layout &quot;special&quot; end ">Copy</button> </div></li> <li><p><code>old_articles_controller.rb</code></p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">class</span> <span class="nc">OldArticlesController</span> <span class="o">&lt;</span> <span class="no">SpecialArticlesController</span> <span class="n">layout</span> <span class="kp">false</span> <span class="k">def</span> <span class="nf">show</span> <span class="vi">@article</span> <span class="o">=</span> <span class="no">Article</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">index</span> <span class="vi">@old_articles</span> <span class="o">=</span> <span class="no">Article</span><span class="p">.</span><span class="nf">older</span> <span class="n">render</span> <span class="ss">layout: </span><span class="s2">"old"</span> <span class="k">end</span> <span class="c1"># ...</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class OldArticlesController < SpecialArticlesController layout false def show @article = Article.find(params[:id]) end def index @old_articles = Article.older render layout: &quot;old&quot; end # ... end ">Copy</button> </div></li> </ul> <p>In this application:</p> <ul> <li>In general, views will be rendered in the <code>main</code> layout</li> <li><code>ArticlesController#index</code> will use the <code>main</code> layout</li> <li><code>SpecialArticlesController#index</code> will use the <code>special</code> layout</li> <li><code>OldArticlesController#show</code> will use no layout at all</li> <li><code>OldArticlesController#index</code> will use the <code>old</code> layout</li> </ul> <h5 id="template-inheritance"><a class="anchorlink" href="#template-inheritance" data-turbo="false"><span>2.2.14.5</span> Template Inheritance</a></h5><p>Similar to the Layout Inheritance logic, if a template or partial is not found in the conventional path, the controller will look for a template or partial to render in its inheritance chain. For example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/controllers/application_controller.rb</span> <span class="k">class</span> <span class="nc">ApplicationController</span> <span class="o">&lt;</span> <span class="no">ActionController</span><span class="o">::</span><span class="no">Base</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class ApplicationController < ActionController::Base end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/controllers/admin_controller.rb</span> <span class="k">class</span> <span class="nc">AdminController</span> <span class="o">&lt;</span> <span class="no">ApplicationController</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class AdminController < ApplicationController end ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight ruby"><span class="c1"># app/controllers/admin/products_controller.rb</span> <span class="k">class</span> <span class="nc">Admin::ProductsController</span> <span class="o">&lt;</span> <span class="no">AdminController</span> <span class="k">def</span> <span class="nf">index</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="class Admin::ProductsController < AdminController def index end end ">Copy</button> </div> <p>The lookup order for an <code>admin/products#index</code> action will be:</p> <ul> <li><code>app/views/admin/products/</code></li> <li><code>app/views/admin/</code></li> <li><code>app/views/application/</code></li> </ul> <p>This makes <code>app/views/application/</code> a great place for your shared partials, which can then be rendered in your ERB as such:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="c">&lt;%# app/views/admin/products/index.html.erb %&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="vi">@products</span> <span class="o">||</span> <span class="s2">"empty_list"</span> <span class="cp">%&gt;</span> <span class="c">&lt;%# app/views/application/_empty_list.html.erb %&gt;</span> There are no items in this list <span class="nt">&lt;em&gt;</span>yet<span class="nt">&lt;/em&gt;</span>. </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render @products || &quot;empty_list&quot; %> There are no items in this list <em>yet</em>. ">Copy</button> </div> <h4 id="avoiding-double-render-errors"><a class="anchorlink" href="#avoiding-double-render-errors" data-turbo="false"><span>2.2.15</span> Avoiding Double Render Errors</a></h4><p>Sooner or later, most Rails developers will see the error message "Can only render or redirect once per action". While this is annoying, it's relatively easy to fix. Usually it happens because of a fundamental misunderstanding of the way that <code>render</code> works.</p><p>For example, here's some code that will trigger this error:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">show</span> <span class="vi">@book</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="k">if</span> <span class="vi">@book</span><span class="p">.</span><span class="nf">special?</span> <span class="n">render</span> <span class="ss">action: </span><span class="s2">"special_show"</span> <span class="k">end</span> <span class="n">render</span> <span class="ss">action: </span><span class="s2">"regular_show"</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def show @book = Book.find(params[:id]) if @book.special? render action: &quot;special_show&quot; end render action: &quot;regular_show&quot; end ">Copy</button> </div> <p>If <code>@book.special?</code> evaluates to <code>true</code>, Rails will start the rendering process to dump the <code>@book</code> variable into the <code>special_show</code> view. But this will <em>not</em> stop the rest of the code in the <code>show</code> action from running, and when Rails hits the end of the action, it will start to render the <code>regular_show</code> view - and throw an error. The solution is simple: make sure that you have only one call to <code>render</code> or <code>redirect</code> in a single code path. One thing that can help is <code>return</code>. Here's a patched version of the method:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">show</span> <span class="vi">@book</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="k">if</span> <span class="vi">@book</span><span class="p">.</span><span class="nf">special?</span> <span class="n">render</span> <span class="ss">action: </span><span class="s2">"special_show"</span> <span class="k">return</span> <span class="k">end</span> <span class="n">render</span> <span class="ss">action: </span><span class="s2">"regular_show"</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def show @book = Book.find(params[:id]) if @book.special? render action: &quot;special_show&quot; return end render action: &quot;regular_show&quot; end ">Copy</button> </div> <p>Note that the implicit render done by ActionController detects if <code>render</code> has been called, so the following will work without errors:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">show</span> <span class="vi">@book</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">find</span><span class="p">(</span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="k">if</span> <span class="vi">@book</span><span class="p">.</span><span class="nf">special?</span> <span class="n">render</span> <span class="ss">action: </span><span class="s2">"special_show"</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def show @book = Book.find(params[:id]) if @book.special? render action: &quot;special_show&quot; end end ">Copy</button> </div> <p>This will render a book with <code>special?</code> set with the <code>special_show</code> template, while other books will render with the default <code>show</code> template.</p><h3 id="using-redirect-to"><a class="anchorlink" href="#using-redirect-to" data-turbo="false"><span>2.3</span> Using <code>redirect_to</code></a></h3><p>Another way to handle returning responses to an HTTP request is with <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionController/Redirecting.html#method-i-redirect_to"><code>redirect_to</code></a>. As you've seen, <code>render</code> tells Rails which view (or other asset) to use in constructing a response. The <code>redirect_to</code> method does something completely different: it tells the browser to send a new request for a different URL. For example, you could redirect from wherever you are in your code to the index of photos in your application with this call:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">redirect_to</span> <span class="n">photos_url</span> </code></pre> <button class="clipboard-button" data-clipboard-text="redirect_to photos_url ">Copy</button> </div> <p>You can use <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionController/Redirecting.html#method-i-redirect_back"><code>redirect_back</code></a> to return the user to the page they just came from. This location is pulled from the <code>HTTP_REFERER</code> header which is not guaranteed to be set by the browser, so you must provide the <code>fallback_location</code> to use in this case.</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">redirect_back</span><span class="p">(</span><span class="ss">fallback_location: </span><span class="n">root_path</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="redirect_back(fallback_location: root_path) ">Copy</button> </div> <div class="interstitial note"><p><code>redirect_to</code> and <code>redirect_back</code> do not halt and return immediately from method execution, but simply set HTTP responses. Statements occurring after them in a method will be executed. You can halt by an explicit <code>return</code> or some other halting mechanism, if needed.</p></div><h4 id="getting-a-different-redirect-status-code"><a class="anchorlink" href="#getting-a-different-redirect-status-code" data-turbo="false"><span>2.3.1</span> Getting a Different Redirect Status Code</a></h4><p>Rails uses HTTP status code 302, a temporary redirect, when you call <code>redirect_to</code>. If you'd like to use a different status code, perhaps 301, a permanent redirect, you can use the <code>:status</code> option:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">redirect_to</span> <span class="n">photos_path</span><span class="p">,</span> <span class="ss">status: </span><span class="mi">301</span> </code></pre> <button class="clipboard-button" data-clipboard-text="redirect_to photos_path, status: 301 ">Copy</button> </div> <p>Just like the <code>:status</code> option for <code>render</code>, <code>:status</code> for <code>redirect_to</code> accepts both numeric and symbolic header designations.</p><h4 id="the-difference-between-render-and-redirect-to"><a class="anchorlink" href="#the-difference-between-render-and-redirect-to" data-turbo="false"><span>2.3.2</span> The Difference Between <code>render</code> and <code>redirect_to</code></a></h4><p>Sometimes inexperienced developers think of <code>redirect_to</code> as a sort of <code>goto</code> command, moving execution from one place to another in your Rails code. This is <em>not</em> correct.</p><p>The current action will complete, returning a response to the browser. After this your code stops running and waits for a new request, it just happens that you've told the browser what request it should make next by sending back an HTTP 302 status code.</p><p>Consider these actions to see the difference:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">index</span> <span class="vi">@books</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">all</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">show</span> <span class="vi">@book</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">find_by</span><span class="p">(</span><span class="ss">id: </span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="k">if</span> <span class="vi">@book</span><span class="p">.</span><span class="nf">nil?</span> <span class="n">render</span> <span class="ss">action: </span><span class="s2">"index"</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def index @books = Book.all end def show @book = Book.find_by(id: params[:id]) if @book.nil? render action: &quot;index&quot; end end ">Copy</button> </div> <p>With the code in this form, there will likely be a problem if the <code>@book</code> variable is <code>nil</code>. Remember, a <code>render :action</code> doesn't run any code in the target action, so nothing will set up the <code>@books</code> variable that the <code>index</code> view will probably require. One way to fix this is to redirect instead of rendering:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">index</span> <span class="vi">@books</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">all</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">show</span> <span class="vi">@book</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">find_by</span><span class="p">(</span><span class="ss">id: </span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="k">if</span> <span class="vi">@book</span><span class="p">.</span><span class="nf">nil?</span> <span class="n">redirect_to</span> <span class="ss">action: :index</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def index @books = Book.all end def show @book = Book.find_by(id: params[:id]) if @book.nil? redirect_to action: :index end end ">Copy</button> </div> <p>With this code, the browser will make a fresh request for the index page, the code in the <code>index</code> method will run, and all will be well.</p><p>The only downside to this code is that it requires a round trip to the browser: the browser requested the show action with <code>/books/1</code> and the controller finds that there are no books, so the controller sends out a 302 redirect response to the browser telling it to go to <code>/books/</code>, the browser complies and sends a new request back to the controller asking now for the <code>index</code> action, the controller then gets all the books in the database and renders the index template, sending it back down to the browser which then shows it on your screen.</p><p>While in a small application, this added latency might not be a problem, it is something to think about if response time is a concern. We can demonstrate one way to handle this with a contrived example:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="k">def</span> <span class="nf">index</span> <span class="vi">@books</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">all</span> <span class="k">end</span> <span class="k">def</span> <span class="nf">show</span> <span class="vi">@book</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">find_by</span><span class="p">(</span><span class="ss">id: </span><span class="n">params</span><span class="p">[</span><span class="ss">:id</span><span class="p">])</span> <span class="k">if</span> <span class="vi">@book</span><span class="p">.</span><span class="nf">nil?</span> <span class="vi">@books</span> <span class="o">=</span> <span class="no">Book</span><span class="p">.</span><span class="nf">all</span> <span class="n">flash</span><span class="p">.</span><span class="nf">now</span><span class="p">[</span><span class="ss">:alert</span><span class="p">]</span> <span class="o">=</span> <span class="s2">"Your book was not found"</span> <span class="n">render</span> <span class="s2">"index"</span> <span class="k">end</span> <span class="k">end</span> </code></pre> <button class="clipboard-button" data-clipboard-text="def index @books = Book.all end def show @book = Book.find_by(id: params[:id]) if @book.nil? @books = Book.all flash.now[:alert] = &quot;Your book was not found&quot; render &quot;index&quot; end end ">Copy</button> </div> <p>This would detect that there are no books with the specified ID, populate the <code>@books</code> instance variable with all the books in the model, and then directly render the <code>index.html.erb</code> template, returning it to the browser with a flash alert message to tell the user what happened.</p><h3 id="using-head-to-build-header-only-responses"><a class="anchorlink" href="#using-head-to-build-header-only-responses" data-turbo="false"><span>2.4</span> Using <code>head</code> to Build Header-Only Responses</a></h3><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionController/Head.html#method-i-head"><code>head</code></a> method can be used to send responses with only headers to the browser. The <code>head</code> method accepts a number or symbol (see <a href="#the-status-option">reference table</a>) representing an HTTP status code. The options argument is interpreted as a hash of header names and values. For example, you can return only an error header:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">head</span> <span class="ss">:bad_request</span> </code></pre> <button class="clipboard-button" data-clipboard-text="head :bad_request ">Copy</button> </div> <p>This would produce the following header:</p><div class="interstitial code"> <pre><code class="highlight http"><span class="k">HTTP</span><span class="o">/</span><span class="m">1.1</span> <span class="m">400</span> <span class="ne">Bad Request</span> <span class="na">Connection</span><span class="p">:</span> <span class="s">close</span> <span class="na">Date</span><span class="p">:</span> <span class="s">Sun, 24 Jan 2010 12:15:53 GMT</span> <span class="na">Transfer-Encoding</span><span class="p">:</span> <span class="s">chunked</span> <span class="na">Content-Type</span><span class="p">:</span> <span class="s">text/html; charset=utf-8</span> <span class="na">X-Runtime</span><span class="p">:</span> <span class="s">0.013483</span> <span class="na">Set-Cookie</span><span class="p">:</span> <span class="s">_blog_session=...snip...; path=/; HttpOnly</span> <span class="na">Cache-Control</span><span class="p">:</span> <span class="s">no-cache</span> </code></pre> <button class="clipboard-button" data-clipboard-text="HTTP/1.1 400 Bad Request Connection: close Date: Sun, 24 Jan 2010 12:15:53 GMT Transfer-Encoding: chunked Content-Type: text/html; charset=utf-8 X-Runtime: 0.013483 Set-Cookie: _blog_session=...snip...; path=/; HttpOnly Cache-Control: no-cache ">Copy</button> </div> <p>Or you can use other HTTP headers to convey other information:</p><div class="interstitial code"> <pre><code class="highlight ruby"><span class="n">head</span> <span class="ss">:created</span><span class="p">,</span> <span class="ss">location: </span><span class="n">photo_path</span><span class="p">(</span><span class="vi">@photo</span><span class="p">)</span> </code></pre> <button class="clipboard-button" data-clipboard-text="head :created, location: photo_path(@photo) ">Copy</button> </div> <p>Which would produce:</p><div class="interstitial code"> <pre><code class="highlight http"><span class="k">HTTP</span><span class="o">/</span><span class="m">1.1</span> <span class="m">201</span> <span class="ne">Created</span> <span class="na">Connection</span><span class="p">:</span> <span class="s">close</span> <span class="na">Date</span><span class="p">:</span> <span class="s">Sun, 24 Jan 2010 12:16:44 GMT</span> <span class="na">Transfer-Encoding</span><span class="p">:</span> <span class="s">chunked</span> <span class="na">Location</span><span class="p">:</span> <span class="s">/photos/1</span> <span class="na">Content-Type</span><span class="p">:</span> <span class="s">text/html; charset=utf-8</span> <span class="na">X-Runtime</span><span class="p">:</span> <span class="s">0.083496</span> <span class="na">Set-Cookie</span><span class="p">:</span> <span class="s">_blog_session=...snip...; path=/; HttpOnly</span> <span class="na">Cache-Control</span><span class="p">:</span> <span class="s">no-cache</span> </code></pre> <button class="clipboard-button" data-clipboard-text="HTTP/1.1 201 Created Connection: close Date: Sun, 24 Jan 2010 12:16:44 GMT Transfer-Encoding: chunked Location: /photos/1 Content-Type: text/html; charset=utf-8 X-Runtime: 0.083496 Set-Cookie: _blog_session=...snip...; path=/; HttpOnly Cache-Control: no-cache ">Copy</button> </div> <h2 id="structuring-layouts"><a class="anchorlink" href="#structuring-layouts" data-turbo="false"><span>3</span> Structuring Layouts</a></h2><p>When Rails renders a view as a response, it does so by combining the view with the current layout, using the rules for finding the current layout that were covered earlier in this guide. Within a layout, you have access to three tools for combining different bits of output to form the overall response:</p> <ul> <li>Asset tags</li> <li><code>yield</code> and <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for"><code>content_for</code></a></li> <li>Partials</li> </ul> <h3 id="asset-tag-helpers"><a class="anchorlink" href="#asset-tag-helpers" data-turbo="false"><span>3.1</span> Asset Tag Helpers</a></h3><p>Asset tag helpers provide methods for generating HTML that link views to feeds, JavaScript, stylesheets, images, videos, and audios. There are six asset tag helpers available in Rails:</p> <ul> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-auto_discovery_link_tag"><code>auto_discovery_link_tag</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-javascript_include_tag"><code>javascript_include_tag</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-stylesheet_link_tag"><code>stylesheet_link_tag</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-image_tag"><code>image_tag</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-video_tag"><code>video_tag</code></a></li> <li><a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-audio_tag"><code>audio_tag</code></a></li> </ul> <p>You can use these tags in layouts or other views, although the <code>auto_discovery_link_tag</code>, <code>javascript_include_tag</code>, and <code>stylesheet_link_tag</code>, are most commonly used in the <code>&lt;head&gt;</code> section of a layout.</p><div class="interstitial warning"><p>The asset tag helpers do <em>not</em> verify the existence of the assets at the specified locations; they simply assume that you know what you're doing and generate the link.</p></div><h4 id="linking-to-feeds-with-the-auto-discovery-link-tag"><a class="anchorlink" href="#linking-to-feeds-with-the-auto-discovery-link-tag" data-turbo="false"><span>3.1.1</span> Linking to Feeds with the <code>auto_discovery_link_tag</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-auto_discovery_link_tag"><code>auto_discovery_link_tag</code></a> helper builds HTML that most browsers and feed readers can use to detect the presence of RSS, Atom, or JSON feeds. It takes the type of the link (<code>:rss</code>, <code>:atom</code>, or <code>:json</code>), a hash of options that are passed through to url_for, and a hash of options for the tag:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">auto_discovery_link_tag</span><span class="p">(</span><span class="ss">:rss</span><span class="p">,</span> <span class="p">{</span><span class="ss">action: </span><span class="s2">"feed"</span><span class="p">},</span> <span class="p">{</span><span class="ss">title: </span><span class="s2">"RSS Feed"</span><span class="p">})</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= auto_discovery_link_tag(:rss, {action: &quot;feed&quot;}, {title: &quot;RSS Feed&quot;}) %> ">Copy</button> </div> <p>There are three tag options available for the <code>auto_discovery_link_tag</code>:</p> <ul> <li><code>:rel</code> specifies the <code>rel</code> value in the link. The default value is "alternate".</li> <li><code>:type</code> specifies an explicit MIME type. Rails will generate an appropriate MIME type automatically.</li> <li><code>:title</code> specifies the title of the link. The default value is the uppercase <code>:type</code> value, for example, "ATOM" or "RSS".</li> </ul> <h4 id="linking-to-javascript-files-with-the-javascript-include-tag"><a class="anchorlink" href="#linking-to-javascript-files-with-the-javascript-include-tag" data-turbo="false"><span>3.1.2</span> Linking to JavaScript Files with the <code>javascript_include_tag</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-javascript_include_tag"><code>javascript_include_tag</code></a> helper returns an HTML <code>script</code> tag for each source provided.</p><p>If you are using Rails with the <a href="asset_pipeline.html">Asset Pipeline</a> enabled, this helper will generate a link to <code>/assets/javascripts/</code> rather than <code>public/javascripts</code> which was used in earlier versions of Rails. This link is then served by the asset pipeline.</p><p>A JavaScript file within a Rails application or Rails engine goes in one of three locations: <code>app/assets</code>, <code>lib/assets</code> or <code>vendor/assets</code>. These locations are explained in detail in the <a href="asset_pipeline.html#asset-organization">Asset Organization section in the Asset Pipeline Guide</a>.</p><p>You can specify a full path relative to the document root, or a URL, if you prefer. For example, to link to a JavaScript file <code>main.js</code> that is inside one of <code>app/assets/javascripts</code>, <code>lib/assets/javascripts</code> or <code>vendor/assets/javascripts</code>, you would do this:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">javascript_include_tag</span> <span class="s2">"main"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= javascript_include_tag &quot;main&quot; %> ">Copy</button> </div> <p>Rails will then output a <code>script</code> tag such as this:</p><div class="interstitial code"> <pre><code class="highlight html"><span class="nt">&lt;script </span><span class="na">src=</span><span class="s">'/assets/main.js'</span><span class="nt">&gt;&lt;/script&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<script src='/assets/main.js'></script> ">Copy</button> </div> <p>The request to this asset is then served by the Sprockets gem.</p><p>To include multiple files such as <code>app/assets/javascripts/main.js</code> and <code>app/assets/javascripts/columns.js</code> at the same time:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">javascript_include_tag</span> <span class="s2">"main"</span><span class="p">,</span> <span class="s2">"columns"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= javascript_include_tag &quot;main&quot;, &quot;columns&quot; %> ">Copy</button> </div> <p>To include <code>app/assets/javascripts/main.js</code> and <code>app/assets/javascripts/photos/columns.js</code>:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">javascript_include_tag</span> <span class="s2">"main"</span><span class="p">,</span> <span class="s2">"/photos/columns"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= javascript_include_tag &quot;main&quot;, &quot;/photos/columns&quot; %> ">Copy</button> </div> <p>To include <code>http://example.com/main.js</code>:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">javascript_include_tag</span> <span class="s2">"http://example.com/main.js"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= javascript_include_tag &quot;http://example.com/main.js&quot; %> ">Copy</button> </div> <h4 id="linking-to-css-files-with-the-stylesheet-link-tag"><a class="anchorlink" href="#linking-to-css-files-with-the-stylesheet-link-tag" data-turbo="false"><span>3.1.3</span> Linking to CSS Files with the <code>stylesheet_link_tag</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-stylesheet_link_tag"><code>stylesheet_link_tag</code></a> helper returns an HTML <code>&lt;link&gt;</code> tag for each source provided.</p><p>If you are using Rails with the "Asset Pipeline" enabled, this helper will generate a link to <code>/assets/stylesheets/</code>. This link is then processed by the Sprockets gem. A stylesheet file can be stored in one of three locations: <code>app/assets</code>, <code>lib/assets</code>, or <code>vendor/assets</code>.</p><p>You can specify a full path relative to the document root, or a URL. For example, to link to a stylesheet file that is inside a directory called <code>stylesheets</code> inside of one of <code>app/assets</code>, <code>lib/assets</code>, or <code>vendor/assets</code>, you would do this:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">stylesheet_link_tag</span> <span class="s2">"main"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= stylesheet_link_tag &quot;main&quot; %> ">Copy</button> </div> <p>To include <code>app/assets/stylesheets/main.css</code> and <code>app/assets/stylesheets/columns.css</code>:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">stylesheet_link_tag</span> <span class="s2">"main"</span><span class="p">,</span> <span class="s2">"columns"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= stylesheet_link_tag &quot;main&quot;, &quot;columns&quot; %> ">Copy</button> </div> <p>To include <code>app/assets/stylesheets/main.css</code> and <code>app/assets/stylesheets/photos/columns.css</code>:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">stylesheet_link_tag</span> <span class="s2">"main"</span><span class="p">,</span> <span class="s2">"photos/columns"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= stylesheet_link_tag &quot;main&quot;, &quot;photos/columns&quot; %> ">Copy</button> </div> <p>To include <code>http://example.com/main.css</code>:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">stylesheet_link_tag</span> <span class="s2">"http://example.com/main.css"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= stylesheet_link_tag &quot;http://example.com/main.css&quot; %> ">Copy</button> </div> <p>By default, the <code>stylesheet_link_tag</code> creates links with <code>rel="stylesheet"</code>. You can override this default by specifying an appropriate option (<code>:rel</code>):</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">stylesheet_link_tag</span> <span class="s2">"main_print"</span><span class="p">,</span> <span class="ss">media: </span><span class="s2">"print"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= stylesheet_link_tag &quot;main_print&quot;, media: &quot;print&quot; %> ">Copy</button> </div> <h4 id="linking-to-images-with-the-image-tag"><a class="anchorlink" href="#linking-to-images-with-the-image-tag" data-turbo="false"><span>3.1.4</span> Linking to Images with the <code>image_tag</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-image_tag"><code>image_tag</code></a> helper builds an HTML <code>&lt;img /&gt;</code> tag to the specified file. By default, files are loaded from <code>public/images</code>.</p><div class="interstitial warning"><p>Note that you must specify the extension of the image.</p></div><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">image_tag</span> <span class="s2">"header.png"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= image_tag &quot;header.png&quot; %> ">Copy</button> </div> <p>You can supply a path to the image if you like:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">image_tag</span> <span class="s2">"icons/delete.gif"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= image_tag &quot;icons/delete.gif&quot; %> ">Copy</button> </div> <p>You can supply a hash of additional HTML options:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">image_tag</span> <span class="s2">"icons/delete.gif"</span><span class="p">,</span> <span class="p">{</span><span class="ss">height: </span><span class="mi">45</span><span class="p">}</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= image_tag &quot;icons/delete.gif&quot;, {height: 45} %> ">Copy</button> </div> <p>You can supply alternate text for the image which will be used if the user has images turned off in their browser. If you do not specify an alt text explicitly, it defaults to the file name of the file, capitalized and with no extension. For example, these two image tags would return the same code:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">image_tag</span> <span class="s2">"home.gif"</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%=</span> <span class="n">image_tag</span> <span class="s2">"home.gif"</span><span class="p">,</span> <span class="ss">alt: </span><span class="s2">"Home"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= image_tag &quot;home.gif&quot; %> <%= image_tag &quot;home.gif&quot;, alt: &quot;Home&quot; %> ">Copy</button> </div> <p>You can also specify a special size tag, in the format "{width}x{height}":</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">image_tag</span> <span class="s2">"home.gif"</span><span class="p">,</span> <span class="ss">size: </span><span class="s2">"50x20"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= image_tag &quot;home.gif&quot;, size: &quot;50x20&quot; %> ">Copy</button> </div> <p>In addition to the above special tags, you can supply a final hash of standard HTML options, such as <code>:class</code>, <code>:id</code>, or <code>:name</code>:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">image_tag</span> <span class="s2">"home.gif"</span><span class="p">,</span> <span class="ss">alt: </span><span class="s2">"Go Home"</span><span class="p">,</span> <span class="ss">id: </span><span class="s2">"HomeImage"</span><span class="p">,</span> <span class="ss">class: </span><span class="s2">"nav_bar"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= image_tag &quot;home.gif&quot;, alt: &quot;Go Home&quot;, id: &quot;HomeImage&quot;, class: &quot;nav_bar&quot; %> ">Copy</button> </div> <h4 id="linking-to-videos-with-the-video-tag"><a class="anchorlink" href="#linking-to-videos-with-the-video-tag" data-turbo="false"><span>3.1.5</span> Linking to Videos with the <code>video_tag</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-video_tag"><code>video_tag</code></a> helper builds an HTML5 <code>&lt;video&gt;</code> tag to the specified file. By default, files are loaded from <code>public/videos</code>.</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">video_tag</span> <span class="s2">"movie.ogg"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= video_tag &quot;movie.ogg&quot; %> ">Copy</button> </div> <p>Produces</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;video</span> <span class="na">src=</span><span class="s">"/videos/movie.ogg"</span> <span class="nt">/&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<video src=&quot;/videos/movie.ogg&quot; /> ">Copy</button> </div> <p>Like an <code>image_tag</code> you can supply a path, either absolute, or relative to the <code>public/videos</code> directory. Additionally you can specify the <code>size: "#{width}x#{height}"</code> option just like an <code>image_tag</code>. Video tags can also have any of the HTML options specified at the end (<code>id</code>, <code>class</code> et al).</p><p>The video tag also supports all of the <code>&lt;video&gt;</code> HTML options through the HTML options hash, including:</p> <ul> <li><code>poster: "image_name.png"</code>, provides an image to put in place of the video before it starts playing.</li> <li><code>autoplay: true</code>, starts playing the video on page load.</li> <li><code>loop: true</code>, loops the video once it gets to the end.</li> <li><code>controls: true</code>, provides browser supplied controls for the user to interact with the video.</li> <li><code>autobuffer: true</code>, the video will pre load the file for the user on page load.</li> </ul> <p>You can also specify multiple videos to play by passing an array of videos to the <code>video_tag</code>:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">video_tag</span> <span class="p">[</span><span class="s2">"trailer.ogg"</span><span class="p">,</span> <span class="s2">"movie.ogg"</span><span class="p">]</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= video_tag [&quot;trailer.ogg&quot;, &quot;movie.ogg&quot;] %> ">Copy</button> </div> <p>This will produce:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;video&gt;</span> <span class="nt">&lt;source</span> <span class="na">src=</span><span class="s">"/videos/trailer.ogg"</span><span class="nt">&gt;</span> <span class="nt">&lt;source</span> <span class="na">src=</span><span class="s">"/videos/movie.ogg"</span><span class="nt">&gt;</span> <span class="nt">&lt;/video&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<video> <source src=&quot;/videos/trailer.ogg&quot;> <source src=&quot;/videos/movie.ogg&quot;> </video> ">Copy</button> </div> <h4 id="linking-to-audio-files-with-the-audio-tag"><a class="anchorlink" href="#linking-to-audio-files-with-the-audio-tag" data-turbo="false"><span>3.1.6</span> Linking to Audio Files with the <code>audio_tag</code></a></h4><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/AssetTagHelper.html#method-i-audio_tag"><code>audio_tag</code></a> helper builds an HTML5 <code>&lt;audio&gt;</code> tag to the specified file. By default, files are loaded from <code>public/audios</code>.</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">audio_tag</span> <span class="s2">"music.mp3"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= audio_tag &quot;music.mp3&quot; %> ">Copy</button> </div> <p>You can supply a path to the audio file if you like:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">audio_tag</span> <span class="s2">"music/first_song.mp3"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= audio_tag &quot;music/first_song.mp3&quot; %> ">Copy</button> </div> <p>You can also supply a hash of additional options, such as <code>:id</code>, <code>:class</code>, etc.</p><p>Like the <code>video_tag</code>, the <code>audio_tag</code> has special options:</p> <ul> <li><code>autoplay: true</code>, starts playing the audio on page load</li> <li><code>controls: true</code>, provides browser supplied controls for the user to interact with the audio.</li> <li><code>autobuffer: true</code>, the audio will pre load the file for the user on page load.</li> </ul> <h3 id="understanding-yield"><a class="anchorlink" href="#understanding-yield" data-turbo="false"><span>3.2</span> Understanding <code>yield</code></a></h3><p>Within the context of a layout, <code>yield</code> identifies a section where content from the view should be inserted. The simplest way to use this is to have a single <code>yield</code>, into which the entire contents of the view currently being rendered is inserted:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;html&gt;</span> <span class="nt">&lt;head&gt;</span> <span class="nt">&lt;/head&gt;</span> <span class="nt">&lt;body&gt;</span> <span class="cp">&lt;%=</span> <span class="k">yield</span> <span class="cp">%&gt;</span> <span class="nt">&lt;/body&gt;</span> <span class="nt">&lt;/html&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<html> <head> </head> <body> <%= yield %> </body> </html> ">Copy</button> </div> <p>You can also create a layout with multiple yielding regions:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;html&gt;</span> <span class="nt">&lt;head&gt;</span> <span class="cp">&lt;%=</span> <span class="k">yield</span> <span class="ss">:head</span> <span class="cp">%&gt;</span> <span class="nt">&lt;/head&gt;</span> <span class="nt">&lt;body&gt;</span> <span class="cp">&lt;%=</span> <span class="k">yield</span> <span class="cp">%&gt;</span> <span class="nt">&lt;/body&gt;</span> <span class="nt">&lt;/html&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<html> <head> <%= yield :head %> </head> <body> <%= yield %> </body> </html> ">Copy</button> </div> <p>The main body of the view will always render into the unnamed <code>yield</code>. To render content into a named <code>yield</code>, call the <code>content_for</code> method with the same argument as the named <code>yield</code>.</p><div class="interstitial note"><p>Newly generated applications will include <code>&lt;%= yield :head %&gt;</code> within the <code>&lt;head&gt;</code> element of its <code>app/views/layouts/application.html.erb</code> template.</p></div><h3 id="using-the-content-for-method"><a class="anchorlink" href="#using-the-content-for-method" data-turbo="false"><span>3.3</span> Using the <code>content_for</code> Method</a></h3><p>The <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for"><code>content_for</code></a> method allows you to insert content into a named <code>yield</code> block in your layout. For example, this view would work with the layout that you just saw:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%</span> <span class="n">content_for</span> <span class="ss">:head</span> <span class="k">do</span> <span class="cp">%&gt;</span> <span class="nt">&lt;title&gt;</span>A simple page<span class="nt">&lt;/title&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> <span class="nt">&lt;p&gt;</span>Hello, Rails!<span class="nt">&lt;/p&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<% content_for :head do %> <title>A simple page</title> <% end %> <p>Hello, Rails!</p> ">Copy</button> </div> <p>The result of rendering this page into the supplied layout would be this HTML:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;html&gt;</span> <span class="nt">&lt;head&gt;</span> <span class="nt">&lt;title&gt;</span>A simple page<span class="nt">&lt;/title&gt;</span> <span class="nt">&lt;/head&gt;</span> <span class="nt">&lt;body&gt;</span> <span class="nt">&lt;p&gt;</span>Hello, Rails!<span class="nt">&lt;/p&gt;</span> <span class="nt">&lt;/body&gt;</span> <span class="nt">&lt;/html&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<html> <head> <title>A simple page</title> </head> <body> <p>Hello, Rails!</p> </body> </html> ">Copy</button> </div> <p>The <code>content_for</code> method is very helpful when your layout contains distinct regions such as sidebars and footers that should get their own blocks of content inserted. It's also useful for inserting page-specific JavaScript <code>&lt;script&gt;</code> elements, CSS <code>&lt;link&gt;</code> elements, context-specific <code>&lt;meta&gt;</code> elements, or any other elements into the <code>&lt;head&gt;</code> of an otherwise generic layout.</p><h3 id="using-partials"><a class="anchorlink" href="#using-partials" data-turbo="false"><span>3.4</span> Using Partials</a></h3><p>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.</p><h4 id="naming-partials"><a class="anchorlink" href="#naming-partials" data-turbo="false"><span>3.4.1</span> Naming Partials</a></h4><p>To render a partial as part of a view, you use the <a href="https://api.rubyonrails.org/v8.0.0/classes/ActionView/Helpers/RenderingHelper.html#method-i-render"><code>render</code></a> method within the view:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="s2">"menu"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render &quot;menu&quot; %> ">Copy</button> </div> <p>This will render a file named <code>_menu.html.erb</code> at that point within the view being rendered. Note the leading underscore character: partials are named with a leading underscore to distinguish them from regular views, even though they are referred to without the underscore. This holds true even when you're pulling in a partial from another folder:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="s2">"application/menu"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render &quot;application/menu&quot; %> ">Copy</button> </div> <p>Since view partials rely on the same <a href="#template-inheritance">Template Inheritance</a> as templates and layouts, that code will pull in the partial from <code>app/views/application/_menu.html.erb</code>.</p><h4 id="using-partials-to-simplify-views"><a class="anchorlink" href="#using-partials-to-simplify-views" data-turbo="false"><span>3.4.2</span> Using Partials to Simplify Views</a></h4><p>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:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="s2">"application/ad_banner"</span> <span class="cp">%&gt;</span> <span class="nt">&lt;h1&gt;</span>Products<span class="nt">&lt;/h1&gt;</span> <span class="nt">&lt;p&gt;</span>Here are a few of our fine products:<span class="nt">&lt;/p&gt;</span> <span class="c">&lt;%# ... %&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="s2">"application/footer"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render &quot;application/ad_banner&quot; %> <h1>Products</h1> <p>Here are a few of our fine products:</p> <%# ... %> <%= render &quot;application/footer&quot; %> ">Copy</button> </div> <p>Here, the <code>_ad_banner.html.erb</code> and <code>_footer.html.erb</code> partials could contain content that is shared by many pages in your application. You don't need to see the details of these sections when you're concentrating on a particular page.</p><p>As seen in the previous sections of this guide, <code>yield</code> is a very powerful tool for cleaning up your layouts. Keep in mind that it's pure Ruby, so you can use it almost everywhere. For example, we can use it to DRY up form layout definitions for several similar resources:</p> <ul> <li><p><code>users/index.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="s2">"application/search_filters"</span><span class="p">,</span> <span class="ss">search: </span><span class="vi">@q</span> <span class="k">do</span> <span class="o">|</span><span class="n">form</span><span class="o">|</span> <span class="cp">%&gt;</span> <span class="nt">&lt;p&gt;</span> Name contains: <span class="cp">&lt;%=</span> <span class="n">form</span><span class="p">.</span><span class="nf">text_field</span> <span class="ss">:name_contains</span> <span class="cp">%&gt;</span> <span class="nt">&lt;/p&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render &quot;application/search_filters&quot;, search: @q do |form| %> <p> Name contains: <%= form.text_field :name_contains %> </p> <% end %> ">Copy</button> </div></li> <li><p><code>roles/index.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="s2">"application/search_filters"</span><span class="p">,</span> <span class="ss">search: </span><span class="vi">@q</span> <span class="k">do</span> <span class="o">|</span><span class="n">form</span><span class="o">|</span> <span class="cp">%&gt;</span> <span class="nt">&lt;p&gt;</span> Title contains: <span class="cp">&lt;%=</span> <span class="n">form</span><span class="p">.</span><span class="nf">text_field</span> <span class="ss">:title_contains</span> <span class="cp">%&gt;</span> <span class="nt">&lt;/p&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render &quot;application/search_filters&quot;, search: @q do |form| %> <p> Title contains: <%= form.text_field :title_contains %> </p> <% end %> ">Copy</button> </div></li> <li><p><code>application/_search_filters.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">form_with</span> <span class="ss">model: </span><span class="n">search</span> <span class="k">do</span> <span class="o">|</span><span class="n">form</span><span class="o">|</span> <span class="cp">%&gt;</span> <span class="nt">&lt;h1&gt;</span>Search form:<span class="nt">&lt;/h1&gt;</span> <span class="nt">&lt;fieldset&gt;</span> <span class="cp">&lt;%=</span> <span class="k">yield</span> <span class="n">form</span> <span class="cp">%&gt;</span> <span class="nt">&lt;/fieldset&gt;</span> <span class="nt">&lt;p&gt;</span> <span class="cp">&lt;%=</span> <span class="n">form</span><span class="p">.</span><span class="nf">submit</span> <span class="s2">"Search"</span> <span class="cp">%&gt;</span> <span class="nt">&lt;/p&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= form_with model: search do |form| %> <h1>Search form:</h1> <fieldset> <%= yield form %> </fieldset> <p> <%= form.submit &quot;Search&quot; %> </p> <% end %> ">Copy</button> </div></li> </ul> <div class="interstitial info"><p>For content that is shared among all pages in your application, you can use partials directly from layouts.</p></div><h4 id="partial-layouts"><a class="anchorlink" href="#partial-layouts" data-turbo="false"><span>3.4.3</span> Partial Layouts</a></h4><p>A partial can use its own layout file, just as a view can use a layout. For example, you might call a partial like this:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="s2">"link_area"</span><span class="p">,</span> <span class="ss">layout: </span><span class="s2">"graybar"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render partial: &quot;link_area&quot;, layout: &quot;graybar&quot; %> ">Copy</button> </div> <p>This would look for a partial named <code>_link_area.html.erb</code> and render it using the layout <code>_graybar.html.erb</code>. Note that layouts for partials follow the same leading-underscore naming as regular partials, and are placed in the same folder with the partial that they belong to (not in the master <code>layouts</code> folder).</p><p>Also note that explicitly specifying <code>:partial</code> is required when passing additional options such as <code>:layout</code>.</p><h4 id="passing-local-variables"><a class="anchorlink" href="#passing-local-variables" data-turbo="false"><span>3.4.4</span> Passing Local Variables</a></h4><p>You can also pass local variables into partials, making them even more powerful and flexible. For example, you can use this technique to reduce duplication between new and edit pages, while still keeping a bit of distinct content:</p> <ul> <li><p><code>new.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;h1&gt;</span>New zone<span class="nt">&lt;/h1&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="s2">"form"</span><span class="p">,</span> <span class="ss">locals: </span><span class="p">{</span><span class="ss">zone: </span><span class="vi">@zone</span><span class="p">}</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<h1>New zone</h1> <%= render partial: &quot;form&quot;, locals: {zone: @zone} %> ">Copy</button> </div></li> <li><p><code>edit.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;h1&gt;</span>Editing zone<span class="nt">&lt;/h1&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="s2">"form"</span><span class="p">,</span> <span class="ss">locals: </span><span class="p">{</span><span class="ss">zone: </span><span class="vi">@zone</span><span class="p">}</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<h1>Editing zone</h1> <%= render partial: &quot;form&quot;, locals: {zone: @zone} %> ">Copy</button> </div></li> <li><p><code>_form.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">form_with</span> <span class="ss">model: </span><span class="n">zone</span> <span class="k">do</span> <span class="o">|</span><span class="n">form</span><span class="o">|</span> <span class="cp">%&gt;</span> <span class="nt">&lt;p&gt;</span> <span class="nt">&lt;b&gt;</span>Zone name<span class="nt">&lt;/b&gt;&lt;br&gt;</span> <span class="cp">&lt;%=</span> <span class="n">form</span><span class="p">.</span><span class="nf">text_field</span> <span class="ss">:name</span> <span class="cp">%&gt;</span> <span class="nt">&lt;/p&gt;</span> <span class="nt">&lt;p&gt;</span> <span class="cp">&lt;%=</span> <span class="n">form</span><span class="p">.</span><span class="nf">submit</span> <span class="cp">%&gt;</span> <span class="nt">&lt;/p&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= form_with model: zone do |form| %> <p> <b>Zone name</b><br> <%= form.text_field :name %> </p> <p> <%= form.submit %> </p> <% end %> ">Copy</button> </div></li> </ul> <p>Although the same partial will be rendered into both views, Action View's submit helper will return "Create Zone" for the new action and "Update Zone" for the edit action.</p><p>To pass a local variable to a partial in only specific cases use the <code>local_assigns</code>.</p> <ul> <li><p><code>index.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="n">user</span><span class="p">.</span><span class="nf">articles</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render user.articles %> ">Copy</button> </div></li> <li><p><code>show.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="n">article</span><span class="p">,</span> <span class="ss">full: </span><span class="kp">true</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render article, full: true %> ">Copy</button> </div></li> <li><p><code>_article.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;h2&gt;</span><span class="cp">&lt;%=</span> <span class="n">article</span><span class="p">.</span><span class="nf">title</span> <span class="cp">%&gt;</span><span class="nt">&lt;/h2&gt;</span> <span class="cp">&lt;%</span> <span class="k">if</span> <span class="n">local_assigns</span><span class="p">[</span><span class="ss">:full</span><span class="p">]</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%=</span> <span class="n">simple_format</span> <span class="n">article</span><span class="p">.</span><span class="nf">body</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="k">else</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%=</span> <span class="n">truncate</span> <span class="n">article</span><span class="p">.</span><span class="nf">body</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<h2><%= article.title %></h2> <% if local_assigns[:full] %> <%= simple_format article.body %> <% else %> <%= truncate article.body %> <% end %> ">Copy</button> </div></li> </ul> <p>This way it is possible to use the partial without the need to declare all local variables.</p><p>Every partial also has a local variable with the same name as the partial (minus the leading underscore). You can pass an object in to this local variable via the <code>:object</code> option:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="s2">"customer"</span><span class="p">,</span> <span class="ss">object: </span><span class="vi">@new_customer</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render partial: &quot;customer&quot;, object: @new_customer %> ">Copy</button> </div> <p>Within the <code>customer</code> partial, the <code>customer</code> variable will refer to <code>@new_customer</code> from the parent view.</p><p>If you have an instance of a model to render into a partial, you can use a shorthand syntax:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="vi">@customer</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render @customer %> ">Copy</button> </div> <p>Assuming that the <code>@customer</code> instance variable contains an instance of the <code>Customer</code> model, this will use <code>_customer.html.erb</code> to render it and will pass the local variable <code>customer</code> into the partial which will refer to the <code>@customer</code> instance variable in the parent view.</p><h4 id="rendering-collections"><a class="anchorlink" href="#rendering-collections" data-turbo="false"><span>3.4.5</span> Rendering Collections</a></h4><p>Partials are very useful in rendering collections. When you pass a collection to a partial via the <code>:collection</code> option, the partial will be inserted once for each member in the collection:</p> <ul> <li><p><code>index.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;h1&gt;</span>Products<span class="nt">&lt;/h1&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="s2">"product"</span><span class="p">,</span> <span class="ss">collection: </span><span class="vi">@products</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<h1>Products</h1> <%= render partial: &quot;product&quot;, collection: @products %> ">Copy</button> </div></li> <li><p><code>_product.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;p&gt;</span>Product Name: <span class="cp">&lt;%=</span> <span class="n">product</span><span class="p">.</span><span class="nf">name</span> <span class="cp">%&gt;</span><span class="nt">&lt;/p&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<p>Product Name: <%= product.name %></p> ">Copy</button> </div></li> </ul> <p>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 <code>_product</code>, and within the <code>_product</code> partial, you can refer to <code>product</code> to get the instance that is being rendered.</p><p>There is also a shorthand for this. Assuming <code>@products</code> is a collection of <code>Product</code> instances, you can simply write this in the <code>index.html.erb</code> to produce the same result:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;h1&gt;</span>Products<span class="nt">&lt;/h1&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="vi">@products</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<h1>Products</h1> <%= render @products %> ">Copy</button> </div> <p>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:</p> <ul> <li><p><code>index.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;h1&gt;</span>Contacts<span class="nt">&lt;/h1&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="p">[</span><span class="n">customer1</span><span class="p">,</span> <span class="n">employee1</span><span class="p">,</span> <span class="n">customer2</span><span class="p">,</span> <span class="n">employee2</span><span class="p">]</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<h1>Contacts</h1> <%= render [customer1, employee1, customer2, employee2] %> ">Copy</button> </div></li> <li><p><code>customers/_customer.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;p&gt;</span>Customer: <span class="cp">&lt;%=</span> <span class="n">customer</span><span class="p">.</span><span class="nf">name</span> <span class="cp">%&gt;</span><span class="nt">&lt;/p&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<p>Customer: <%= customer.name %></p> ">Copy</button> </div></li> <li><p><code>employees/_employee.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;p&gt;</span>Employee: <span class="cp">&lt;%=</span> <span class="n">employee</span><span class="p">.</span><span class="nf">name</span> <span class="cp">%&gt;</span><span class="nt">&lt;/p&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<p>Employee: <%= employee.name %></p> ">Copy</button> </div></li> </ul> <p>In this case, Rails will use the customer or employee partials as appropriate for each member of the collection.</p><p>In the event that the collection is empty, <code>render</code> will return nil, so it should be fairly simple to provide alternative content.</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;h1&gt;</span>Products<span class="nt">&lt;/h1&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span><span class="p">(</span><span class="vi">@products</span><span class="p">)</span> <span class="o">||</span> <span class="s2">"There are no products available."</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<h1>Products</h1> <%= render(@products) || &quot;There are no products available.&quot; %> ">Copy</button> </div> <h4 id="local-variables"><a class="anchorlink" href="#local-variables" data-turbo="false"><span>3.4.6</span> Local Variables</a></h4><p>To use a custom local variable name within the partial, specify the <code>:as</code> option in the call to the partial:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="s2">"product"</span><span class="p">,</span> <span class="ss">collection: </span><span class="vi">@products</span><span class="p">,</span> <span class="ss">as: :item</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render partial: &quot;product&quot;, collection: @products, as: :item %> ">Copy</button> </div> <p>With this change, you can access an instance of the <code>@products</code> collection as the <code>item</code> local variable within the partial.</p><p>You can also pass in arbitrary local variables to any partial you are rendering with the <code>locals: {}</code> option:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="s2">"product"</span><span class="p">,</span> <span class="ss">collection: </span><span class="vi">@products</span><span class="p">,</span> <span class="ss">as: :item</span><span class="p">,</span> <span class="ss">locals: </span><span class="p">{</span><span class="ss">title: </span><span class="s2">"Products Page"</span><span class="p">}</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render partial: &quot;product&quot;, collection: @products, as: :item, locals: {title: &quot;Products Page&quot;} %> ">Copy</button> </div> <p>In this case, the partial will have access to a local variable <code>title</code> with the value "Products Page".</p><h4 id="counter-variables"><a class="anchorlink" href="#counter-variables" data-turbo="false"><span>3.4.7</span> Counter Variables</a></h4><p>Rails also makes a counter variable available within a partial called by the collection. The variable is named after the title of the partial followed by <code>_counter</code>. For example, when rendering a collection <code>@products</code> the partial <code>_product.html.erb</code> can access the variable <code>product_counter</code>. The variable indexes the number of times the partial has been rendered within the enclosing view, starting with a value of <code>0</code> on the first render.</p><div class="interstitial code"> <pre><code class="highlight erb"># index.html.erb <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="s2">"product"</span><span class="p">,</span> <span class="ss">collection: </span><span class="vi">@products</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="# index.html.erb <%= render partial: &quot;product&quot;, collection: @products %> ">Copy</button> </div> <div class="interstitial code"> <pre><code class="highlight erb"># _product.html.erb <span class="cp">&lt;%=</span> <span class="n">product_counter</span> <span class="cp">%&gt;</span> # 0 for the first product, 1 for the second product... </code></pre> <button class="clipboard-button" data-clipboard-text="# _product.html.erb <%= product_counter %> # 0 for the first product, 1 for the second product... ">Copy</button> </div> <p>This also works when the local variable name is changed using the <code>as:</code> option. So if you did <code>as: :item</code>, the counter variable would be <code>item_counter</code>.</p><h4 id="spacer-templates"><a class="anchorlink" href="#spacer-templates" data-turbo="false"><span>3.4.8</span> Spacer Templates</a></h4><p>You can also specify a second partial to be rendered between instances of the main partial by using the <code>:spacer_template</code> option:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="vi">@products</span><span class="p">,</span> <span class="ss">spacer_template: </span><span class="s2">"product_ruler"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render partial: @products, spacer_template: &quot;product_ruler&quot; %> ">Copy</button> </div> <p>Rails will render the <code>_product_ruler</code> partial (with no data passed in to it) between each pair of <code>_product</code> partials.</p><h4 id="collection-partial-layouts"><a class="anchorlink" href="#collection-partial-layouts" data-turbo="false"><span>3.4.9</span> Collection Partial Layouts</a></h4><p>When rendering collections it is also possible to use the <code>:layout</code> option:</p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">partial: </span><span class="s2">"product"</span><span class="p">,</span> <span class="ss">collection: </span><span class="vi">@products</span><span class="p">,</span> <span class="ss">layout: </span><span class="s2">"special_layout"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<%= render partial: &quot;product&quot;, collection: @products, layout: &quot;special_layout&quot; %> ">Copy</button> </div> <p>The layout will be rendered together with the partial for each item in the collection. The current object and object_counter variables will be available in the layout as well, the same way they are within the partial.</p><h3 id="using-nested-layouts"><a class="anchorlink" href="#using-nested-layouts" data-turbo="false"><span>3.5</span> Using Nested Layouts</a></h3><p>You may find that your application requires a layout that differs slightly from your regular application layout to support one particular controller. Rather than repeating the main layout and editing it, you can accomplish this by using nested layouts (sometimes called sub-templates). Here's an example:</p><p>Suppose you have the following <code>ApplicationController</code> layout:</p> <ul> <li><p><code>app/views/layouts/application.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="nt">&lt;html&gt;</span> <span class="nt">&lt;head&gt;</span> <span class="nt">&lt;title&gt;</span><span class="cp">&lt;%=</span> <span class="vi">@page_title</span> <span class="ow">or</span> <span class="s2">"Page Title"</span> <span class="cp">%&gt;</span><span class="nt">&lt;/title&gt;</span> <span class="cp">&lt;%=</span> <span class="n">stylesheet_link_tag</span> <span class="s2">"layout"</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%=</span> <span class="k">yield</span> <span class="ss">:head</span> <span class="cp">%&gt;</span> <span class="nt">&lt;/head&gt;</span> <span class="nt">&lt;body&gt;</span> <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">"top_menu"</span><span class="nt">&gt;</span>Top menu items here<span class="nt">&lt;/div&gt;</span> <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">"menu"</span><span class="nt">&gt;</span>Menu items here<span class="nt">&lt;/div&gt;</span> <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">"content"</span><span class="nt">&gt;</span><span class="cp">&lt;%=</span> <span class="n">content_for?</span><span class="p">(</span><span class="ss">:content</span><span class="p">)</span> <span class="p">?</span> <span class="k">yield</span><span class="p">(</span><span class="ss">:content</span><span class="p">)</span> <span class="p">:</span> <span class="k">yield</span> <span class="cp">%&gt;</span><span class="nt">&lt;/div&gt;</span> <span class="nt">&lt;/body&gt;</span> <span class="nt">&lt;/html&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<html> <head> <title><%= @page_title or &quot;Page Title&quot; %></title> <%= stylesheet_link_tag &quot;layout&quot; %> <%= yield :head %> </head> <body> <div id=&quot;top_menu&quot;>Top menu items here</div> <div id=&quot;menu&quot;>Menu items here</div> <div id=&quot;content&quot;><%= content_for?(:content) ? yield(:content) : yield %></div> </body> </html> ">Copy</button> </div></li> </ul> <p>On pages generated by <code>NewsController</code>, you want to hide the top menu and add a right menu:</p> <ul> <li><p><code>app/views/layouts/news.html.erb</code></p><div class="interstitial code"> <pre><code class="highlight erb"><span class="cp">&lt;%</span> <span class="n">content_for</span> <span class="ss">:head</span> <span class="k">do</span> <span class="cp">%&gt;</span> <span class="nt">&lt;style&gt;</span> <span class="nf">#top_menu</span> <span class="p">{</span><span class="nl">display</span><span class="p">:</span> <span class="nb">none</span><span class="p">}</span> <span class="nf">#right_menu</span> <span class="p">{</span><span class="nl">float</span><span class="p">:</span> <span class="nb">right</span><span class="p">;</span> <span class="nl">background-color</span><span class="p">:</span> <span class="no">yellow</span><span class="p">;</span> <span class="nl">color</span><span class="p">:</span> <span class="no">black</span><span class="p">}</span> <span class="nt">&lt;/style&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="n">content_for</span> <span class="ss">:content</span> <span class="k">do</span> <span class="cp">%&gt;</span> <span class="nt">&lt;div</span> <span class="na">id=</span><span class="s">"right_menu"</span><span class="nt">&gt;</span>Right menu items here<span class="nt">&lt;/div&gt;</span> <span class="cp">&lt;%=</span> <span class="n">content_for?</span><span class="p">(</span><span class="ss">:news_content</span><span class="p">)</span> <span class="p">?</span> <span class="k">yield</span><span class="p">(</span><span class="ss">:news_content</span><span class="p">)</span> <span class="p">:</span> <span class="k">yield</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%</span> <span class="k">end</span> <span class="cp">%&gt;</span> <span class="cp">&lt;%=</span> <span class="n">render</span> <span class="ss">template: </span><span class="s2">"layouts/application"</span> <span class="cp">%&gt;</span> </code></pre> <button class="clipboard-button" data-clipboard-text="<% content_for :head do %> <style> #top_menu {display: none} #right_menu {float: right; background-color: yellow; color: black} </style> <% end %> <% content_for :content do %> <div id=&quot;right_menu&quot;>Right menu items here</div> <%= content_for?(:news_content) ? yield(:news_content) : yield %> <% end %> <%= render template: &quot;layouts/application&quot; %> ">Copy</button> </div></li> </ul> <p>That's it. The News views will use the new layout, hiding the top menu and adding a new right menu inside the "content" div.</p><p>There are several ways of getting similar results with different sub-templating schemes using this technique. Note that there is no limit in nesting levels. One can use the <code>ActionView::render</code> method via <code>render template: 'layouts/news'</code> to base a new layout on the News layout. If you are sure you will not subtemplate the <code>News</code> layout, you can replace the <code>content_for?(:news_content) ? yield(:news_content) : yield</code> with simply <code>yield</code>.</p> </section> <hr> <footer aria-labelledby="heading-feedback" role="region"> <h2 id="heading-feedback">Feedback</h2> <p> You're encouraged to help improve the quality of this guide. </p> <p> Please contribute if you see any typos or factual errors. To get started, you can read our <a href="https://edgeguides.rubyonrails.org/contributing_to_ruby_on_rails.html#contributing-to-the-rails-documentation">documentation contributions</a> section. </p> <p> You may also find incomplete content or stuff that is not up to date. Please do add any missing documentation for main. Make sure to check <a href="https://edgeguides.rubyonrails.org">Edge Guides</a> first to verify if the issues are already fixed or not on the main branch. Check the <a href="ruby_on_rails_guides_guidelines.html">Ruby on Rails Guides Guidelines</a> for style and conventions. </p> <p> If for whatever reason you spot something to fix but cannot patch it yourself, please <a href="https://github.com/rails/rails/issues">open an issue</a>. </p> <p>And last but not least, any kind of discussion regarding Ruby on Rails documentation is very welcome on the <a href="https://discuss.rubyonrails.org/c/rubyonrails-docs">official Ruby on Rails Forum</a>. </p> </footer> </div> </article> </main> <hr class="hide" /> <footer id="complementary"> <div class="wrapper"> <p>This work is licensed under a <a href="https://creativecommons.org/licenses/by-sa/4.0/">Creative Commons Attribution-ShareAlike 4.0 International</a> License</p> <p>"Rails", "Ruby on Rails", and the Rails logo are trademarks of David Heinemeier Hansson. All rights reserved.</p> </div> </footer> <a href="#main-skip-link" class="back-to-top" data-turbo="false"><span class="visibly-hidden">Back to top</span></a> </body> </html>

Pages: 1 2 3 4 5 6 7 8 9 10