Ruby on Rails asset pipeline doesn't work properly

元气小坏坏 提交于 2019-12-12 06:15:27

问题


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.


回答1:


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'



回答2:


You can remove the animals.coffee file and animals.js can be require in the file of application.js to available your js code in your project.



来源:https://stackoverflow.com/questions/44231490/ruby-on-rails-asset-pipeline-doesnt-work-properly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!