htmlruby-on-railsviewactioncontroller

Cannot access instance variable on view using custom layout on Rails


I have a controller method with custom layout and I cannot access the instance variables on corresponding views.

When I changed back to the default application layout. I can access the instance variables.

pages_controller.rb

def payment_summary
    render layout: "content"
    if session[:new_company_id].present?
      @company = Company.find(session[:new_company_id])
    end
    @var = "this is test"
  end

payment_summary.html.erb

  <div class="row">
    <div class="col-sm">
      Company Info
      <div class="card">
        <%= @company.name %>
        <%= @var %>
      </div>
    </div>
    <div class="col-sm">
      Due Today
    </div>
  </div>

layouts/content.html.erb

<!DOCTYPE html>
<html>
  <head>
   
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
    <!-- Font Awesome 5 Free -->
    <script src="https://kit.fontawesome.com/9da10782cc.js"></script>
    <!-- for js cookie use -->
    <script src="https://cdn.jsdelivr.net/npm/js-cookie@2/src/js.cookie.min.js"></script>

  </head>

  <body class="content-pages <%= body_class %>">
    <%= yield %>
  </body>
</html>

When I remove, render layout content everything works fine.


Solution

  • render in this case is "order dependent". Move it down, as the last statement within your action body:

    def payment_summary
      if session[:new_company_id].present?
        @company = Company.find(session[:new_company_id])
      end
      @var = "this is test"
      render layout: "content"
    end