Search code examples
ruby-on-railsactioncontrollerruby-on-rails-5

Rails Member Route Breaks Layout in Rails 5.1


I have a rails controller named "claims" and an action named "addservice". as shown below

class ClaimsController < ApplicationController
  before_action :set_claim, only: [:show, :edit, :update, :destroy]

  layout 'dashboard'

  def addservice
  end

  def new
  end
end

Then in my route.rb file i have the following routes

resources :claims do 
  member do 
    get 'addService'
  end 
end 

But the problem is whenever I visit the addservice route at

localhost:3000/claims/1/addservice

for example, the static asset links in my dashboard layout breaks. And from the terminal I see the asset links are now namespaced as shown below with a new 'claims' directory added before the actual locations causing the links to the static files to break.

ActionController::RoutingError (No route matches [GET] "/claims/asset/plugins/style/css/style.css"):

It works normally when I visit the new action in the claims controller and others but never for the namespaced route.

The links in my dashboard.html.erb layout file are shown below:

<link href="../asset/plugins/style/css/style.css" rel="stylesheet">
<link href="../asset/plugins/css/bootstrap-extension.css" rel="stylesheet">      

etc.


Solution

  • You have to remove these stylesheets from dashboard layout files

    <link href="../asset/plugins/style/css/style.css" rel="stylesheet">
    <link href="../asset/plugins/css/bootstrap-extension.css" rel="stylesheet">
    

    And now you can create a new css files inside the app/assets/stylesheets directory

    # app/assets/stylesheets/dashboard.css
    
    /*
    *= require dashboard/style
    *= require dashboard/bootstrap-extension
    */
    

    Now you can create a dashboard directory inside the app/assets/stylesheets directory and place those files inside the dashboard directory.

    Now add dashboard css file to assets initializers for assets precompile

    # config/initializers/assets.rb
    Rails.application.config.assets.precompile += %w( dashboard.css )
    

    Add dashboard css file to dashboard layout -

    # app/views/layouts/dashboard.html.erb  
    <%= stylesheet_link_tag 'dashboard', media: 'all'%>
    

    Hope it should work.