Search code examples
javascriptruby-on-railscoffeescriptasset-pipelineassets

Ruby on Rails asset pipeline doesn't work properly


I have been working on a ruby on rails project just now. I have created a controller named 'animals' and a view (index.html.erb) for index action. I don't want to include 'application' javascript file.

So I created animals.js

The file's content is

//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require bootstrap-sprockets
//= animals.coffee

I have also added animals.js and animals.css to asset.rb

Rails.application.config.assets.precompile += %w( animals.js )
Rails.application.config.assets.precompile += %w( animals.css )

My index.html.erb contains following lines

<%= stylesheet_link_tag 'animals', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'animals', 'data-turbolinks-track' => true %>

When I inspected source html code generated by server, I have seen that jquery scipts hadn't been included in the page. It was just animal.js file.

<head>
   <meta name="viewport" content="width=device-width, initial-  scale=1.0">
   <title>Rails Omniauth</title>
   <meta name="description" content="Rails Omniauth">
   <link rel="stylesheet" media="all" href="/assets/animals.self-e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b5433a495991b7852b855.css?body=1" data-turbolinks-track="true">
   <script src="/assets/animals.self-1d93d37bf2f830ac42e82eb68e3bb0040ece5d23533a05bf77f7407fd59178d3.js?body=1" data-turbolinks-track="true"></script>

</head>

Any suggestions why these scripts had been inclued ?

Thanks.


Solution

  • I think your issue might be that you have two files with the same name (but different extensions). Since the Rails asset helpers treat coffescript and js files equally this is ambiguous:

    <%= javascript_include_tag 'animals', 'data-turbolinks-track' => true %>
    

    Which file should it load? I'm guessing it takes the first in alphabetical order which would be animals.coffee.

    To solve the issue move the sprockets manifest to animals.coffee and remove the animals.js file.

    # app/assets/animals.coffee
    #= require jquery
    #= require jquery_ujs
    #= require turbolinks
    #= require bootstrap-sprockets
    #= require_self
    alert 'Hello World'