Search code examples
cssruby-on-railsruby-on-rails-5asset-pipelineturbolinks

Asset not loaded with redirect_to with different layout in rails 5


Currently, I have 2 layouts say 'devise'(For not authenticated pages) and 'application'(For all pages after the login). For some reason after login when redirect_to root_url is executed the dashboard is loaded but any CSS and jQuery is not loaded. After refreshing the page, everything works fine. I am not sure what is causing this. Any help would be appreciated. Thanks in advance.

This is layout my files.

1. devise.html.erb

<head>
  <title></title>
  <%= csrf_meta_tags %>
  <%= csp_meta_tag %>

  <!-- Main css styles -->
  <%= stylesheet_link_tag  'devise' %>

  <!-- Main javascript files -->
  <%= javascript_include_tag 'devise' %>
</head>

2. application.html.erb

<head>
   <title></title>
   <%= csrf_meta_tags %>
   <%= csp_meta_tag %>
   <!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->

   <!-- Main css styles -->
   <%= stylesheet_link_tag 'application'%>
   <%= javascript_include_tag 'application' %>
</head>

Solution

  • Turbolinks works best when your JavaScript and CSS are consistent across different templates. If you must significantly change your scripts and styles between layouts I recommend that you add data-turbolinks-track="reload" to your asset tags:

    <head>
      <title></title>
      <%= csrf_meta_tags %>
      <%= csp_meta_tag %>
    
      <!-- Main css styles -->
     <%= stylesheet_link_tag 'devise', 'data-turbolinks-track': 'reload' %>
    
      <!-- Main javascript files -->
      <%= javascript_include_tag 'devise', 'data-turbolinks-track': 'reload' %>
    </head>
    

    <head>
       <title></title>
       <%= csrf_meta_tags %>
       <%= csp_meta_tag %>
       <!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
    
       <!-- Main css styles -->
       <%= stylesheet_link_tag 'application', 'data-turbolinks-track': 'reload' %>
       <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload'  %>
    </head>
    

    When Turbolinks notices a difference between a new page and the previous one, it will reload the page. This is also important to ensure that users download the most recently deployed assets.