Rails: Set a common or global instance variable across several controller actions

前端 未结 4 1184
萌比男神i
萌比男神i 2020-12-14 03:02

How should one have several different controller\' actions set a common instance variable for use in templates but after the action runs.

4条回答
  •  孤城傲影
    2020-12-14 03:38

    I had this challenge when working on a Rails 6 application.

    I wanted to use an instance variable in a partial (app/views/shared/_header.html.erb) that was defined in a different controller (app/controllers/categories_controller.rb).

    The instance variable that I wanted to use is @categories which is defined as:

    # app/controllers/categories_controller.rb
    
    class CategoriesController < ApplicationController
    
      def index
        @categories = Category.all
      end
      .
      .
      .
    end
    

    Here's how I did it:

    Firstly, I defined a helper_method for the instance variable in my app/controllers/application_controller.rb file:

    class ApplicationController < ActionController::Base
      helper_method :categories
    
      def categories
        @categories = Category.all
      end
    end
    

    This made the @categories instance variable globally available as categories to every controller action and views:

    Next,I rendered the app/views/shared/_header.html.erb partial in the app/views/layouts/application.html.erb this way:

    <%= render partial: '/shared/header' %>
    

    This also makes the @categories instance variable globally available as categories become available to every controller views that will use the partial without the need to define the @categories instance variable in the respective controllers of the views.

    So I used the @categories instance variable globally available as categories in the partial this way:

    # app/views/shared/_header.html.erb
    
    <% categories.each do |category| %>
      <%= link_to category do %>
        <%= category.name %>
      <% end %>
    <% end %>
    

    Note: You can use locals to pass in the variables into the partials:

    <%= render partial: '/shared/header', locals: { categories: @categories } %>
    

    However, this will require a controller action that sets a @categories instance variable for every controller views that will use the partial.

    You can read up more about Helpers and Helper Methods in the Rails Official Documentation: https://api.rubyonrails.org/classes/AbstractController/Helpers/ClassMethods.html

    That's all.

    I hope this helps

提交回复
热议问题