Rails 4 : 자산이 생산에 적재되지 않음
앱을 프로덕션에 배치하려고하는데 이미지 및 CSS 자산 경로가 작동하지 않습니다.
내가 현재하고있는 일은 다음과 같습니다.
- 이미지 자산은 /app/assets/images/image.jpg에 있습니다.
- 스타일 시트는 /app/assets/stylesheets/style.css에 있습니다.
- 내 레이아웃에서는 다음과 같이 CSS 파일을 참조합니다.
<%= stylesheet_link_tag "styles", media: "all", "data-turbolinks-track" => true %>
- 유니콘을 다시 시작하기 전에 실행
RAILS_ENV=production bundle exec rake assets:precompile
하면 성공하고public/assets
디렉토리에 지문 파일이 표시됩니다 .
내 사이트를 탐색 할 때에 대한 404 찾을 수 없음 오류가 발생합니다 mysite.com/stylesheets/styles.css
.
내가 뭘 잘못하고 있죠?
업데이트 : 내 레이아웃에서는 다음과 같습니다.
<%= stylesheet_link_tag "bootstrap.min", media: "all", "data-turbolinks-track" => true %>
<%= stylesheet_link_tag "styles", media: "all", "data-turbolinks-track" => true %>
<%= javascript_include_tag "application", "data-turbolinks-track" => true %>
생성 소스는 다음과 같습니다.
<link data-turbolinks-track="true" href="/stylesheets/bootstrap.min.css" media="all" rel="stylesheet" />
<link data-turbolinks-track="true" href="/stylesheets/styles.css" media="all" rel="stylesheet" />
<script data-turbolinks-track="true" src="/assets/application-0c647c942c6eff10ad92f1f2b0c64efe.js"></script>
Rails가 컴파일 된 CSS 파일을 제대로 찾지 못하는 것 같습니다. 그러나 왜 자바 스크립트 (정확한 /assets/****.js
경로) 에서 올바르게 작동하는지 혼란 스럽 습니다 .
레일 4에서 아래 사항을 변경해야합니다.
config.assets.compile = true
config.assets.precompile = ['*.js', '*.css', '*.css.erb']
이것은 나와 함께 작동합니다. 다음 명령을 사용하여 자산을 사전 컴파일하십시오
RAILS_ENV=production bundle exec rake assets:precompile
행운을 빕니다!
방금 동일한 문제가 있었고 config / environments / production.rb에서이 설정을 찾았습니다.
# Rails 4:
config.serve_static_assets = false
# Or for Rails 5:
config.public_file_server.enabled = false
true
작동 하도록 변경했습니다 . 기본적으로 Rails는 파일을 Rails 앱으로 프록시하는 대신 공용 폴더에서 파일 요청을 처리하도록 프론트 엔드 웹 서버를 구성한 것으로 보입니다. 아마도 CSS 스타일 시트가 아닌 자바 스크립트 파일에 대해이 작업을 수행 했습니까?
( Rails 5 설명서 참조 ) 주석에서 언급했듯이 Rails 5 RAILS_SERVE_STATIC_FILES
에서는 기본 설정이이므로 환경 변수를 설정할 수 있습니다 config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
.
에서 /config/environments/production.rb
나는이를 추가했다 :
Rails.application.config.assets.precompile += %w( *.js ^[^_]*.css *.css.erb )
.js는 이미 사전 컴파일되고 있지만 어쨌든 추가했습니다. .css 및 .css.erb는 자동으로 발생하지 않습니다. 이 ^[^_]
부분은 컴파일되는 부분을 제외합니다. 정규 표현식입니다.
문서에 자산 파이프 라인이 기본적으로 활성화되어 있지만 Javascript에만 적용된다는 사실을 명확하게 밝히지 않는다는 문서가 명확하지 않은 것은 약간 실망 스럽습니다.
: 나는 변경하여이 문제를 해결할 수있었습니다 config.assets.compile = false
에
config.assets.compile = true
의/config/environments/production.rb
업데이트 (2018 년 6 월 24 일) :이 방법 은 사용중인 Sprockets 버전이 2.12.5, 3.7.2 또는 4.0.0.beta8 미만인 경우 보안 취약점을 만듭니다 .
Rails 5의 경우 다음 구성 코드를 활성화해야합니다.
config.public_file_server.enabled = true
기본적으로 Rails 5는 다음 구성 라인과 함께 제공됩니다.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
따라서 환경 변수 RAILS_SERVE_STATIC_FILES
를 true 로 설정해야 합니다.
프로덕션에서 자산을 제공하기 위해 수행해야하는 두 가지가 있습니다.
- 자산을 사전 컴파일하십시오.
- 서버의 자산을 브라우저에 제공하십시오.
1) 자산을 사전 컴파일하기 위해 몇 가지 선택 사항이 있습니다.
당신은 실행할 수 있습니다
rake assets:precompile
다음, 소스 코드 제어 (자식)에 커밋, 로컬 컴퓨터에 예를 들어, 카피 스트라 노를 들어, 배포 프로그램을 실행합니다. 사전 컴파일 된 자산을 SCM에 커밋하는 좋은 방법은 아닙니다.You can write a rake task that run
RAILS_ENV=production rake assets:precompile
on the target servers each time you deploy your Rails app to production, before you restart the server.
Code in a task for capistrano will look similar to this:
on roles(:app) do
if DEPLOY_ENV == 'production'
execute("cd #{DEPLOY_TO_DIR}/current && RAILS_ENV=production rvm #{ruby_string} do rake assets:precompile")
end
end
2) Now, you have the assets on production servers, you need to serve them to browser.
Again, you have several choices.
Turn on Rails static file serving in config/environments/production.rb
config.serve_static_assets = true # old or config.serve_static_files = true # new
Using Rails to serve static files will kill your Rails app performance.
Configure nginx (or Apache) to serve static files.
For example, my nginx that was configured to work with Puma looks like this:
location ~ ^/(assets|images|fonts)/(.*)$ { alias /var/www/foster_care/current/public/$1/$2; gzip on; expires max; add_header Cache-Control public; }
Rails 4 no longer generates the non fingerprinted version of the asset: stylesheets/style.css will not be generated for you.
If you use stylesheet_link_tag
then the correct link to your stylesheet will be generated
In addition styles.css
should be in config.assets.precompile
which is the list of things that are precompiled
change your Production.rb file line
config.assets.compile = false
into
config.assets.compile = true
and also add
config.assets.precompile = ['*.js', '*.css', '*.css.erb']
What you SHOULD NOT do:
Some of my colleagues above have recommended you to do this:
config.serve_static_assets = true ## DON”T DO THIS!!
config.public_file_server.enabled = true ## DON”T DO THIS!!
The rails asset pipeline says of the above approach:
This mode uses more memory, performs more poorly than the default and is not recommended. See here: (http://edgeguides.rubyonrails.org/asset_pipeline.html#live-compilation)
What you SHOULD do:
Precompile your assets.
RAILS_ENV=production rake assets:precompile
You can probably do that with a rake task.
I'm running Ubuntu Server 14.04, Ruby 2.2.1 and Rails 4.2.4 I have followed a deploy turorial from DigitalOcean and everything went well but when I go to the browser and enter the IP address of my VPS my app is loaded but without styles and javascript.
The app is running with Unicorn and Nginx. To fix this problem I entered my server using SSH with my user 'deployer' and go to my app path which is '/home/deployer/apps/blog' and run the following command:
RAILS_ENV=production bin/rake assets:precompile
Then I just restart the VPS and that's it! It works for me!
Hope it could be useful for somebody else!
If precompile is set you DO NOT need
config.assets.compile = true
as this is to serve assets live.
Our problem was we only had development secret key base set in config/secrets.yml
development:
secret_key_base: '83d141eeb181032f4070ae7b1b27d9ff'
Need entry for production environment
The default matcher for compiling files includes application.js, application.css and all non-JS/CSS files (this will include all image assets automatically) from app/assets folders including your gems:
If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the precompile array in config/initializers/assets.rb:
Rails.application.config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets
First of all check your assets, it might be possible there is some error in pre-compiling of assets.
To pre-compile assets in production ENV run this command:
RAILS_ENV=production rake assets:precompile
If it shows error, remove that first,
In case of "undefined variable" error, load that variable file before using it in another file.
example:
@import "variables";
@import "style";
in application.rb file set sequence of pre-compiliation of assets
example:
config.assets.precompile += [ 'application.js', 'admin.js', 'admin/events.js', 'admin/gallery.js', 'frontendgallery.js']
config.assets.precompile += [ 'application.css', 'admin.css','admin/events.css', 'admin/gallery.css', 'frontendgallery.css']
Found this:
The configuration option config.serve_static_assets
has been renamed to config.serve_static_files
to clarify its role.
in config/environments/production.rb
:
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present?
So set env RAILS_SERVE_STATIC_FILES
or using Nginx
to serving static files. Add config.serve_static_assets = true
will still work, but removed in future.
it is not recommended to let capistrano do assets precompile, because it may take ages and often time out. try to do local assets precompile.
1st, set in config/application.rb config.assets.initialize_on_precompile = false
then do local RAILS_ENV=production bin/rake assets:precompile
and add those public/assets to git.
and config/environments/development.rb, change your asset path to avoid using precompiled assets:
config.assets.prefix = '/dev-assets'
If you have db connection issue, means u have initializer that uses db. one way around it is to set a new environment by duplicate production.rb as maybe production2.rb, and in database.yml, add production2 environment with development db setting. then do
RAILS_ENV=production2 bin/rake assets:precompile
if you are still facing some issue with assets, for example ckeditor, add the js file into config/initializers/assets.rb
Rails.application.config.assets.precompile += %w( ckeditor.js )
I may be wrong but those who recommend changing
config.assets.compile = true
The comment on this line reads: #Do not fallback to assets pipeline if a precompiled asset is missed.
This suggests that by setting this to true you are not fixing the problem but rather bypassing it and running the pipeline every time. This must surely kill your performance and defeat the purpose of the pipeline?
I had this same error and it was due to the application running in a sub folder that rails didn't know about.
So my css file where in home/subfolder/app/public/.... but rails was looking in home/app/public/...
try either moving your app out of the subfolder or telling rails that it is in a subfolder.
location ~ ^/assets/ {
expires 1y;
add_header Cache-Control public;
add_header ETag "";
}
This fixed the problem for me in production. Put it into the nginx config.
Even we faced the same problem where RAILS_ENV=production bundle exec rake assets:precompile
succeeded but things did not work as expected.
We found that unicorn was the main culprit here.
Same as your case, even we used to restart unicorn after compiling the assets. It was noticed that when unicorn is restarted, only its worker processes are restarted and not the master process.
This is the main reason the correct assets are not served.
Later, after compiling assets, we stopped and started unicorn so that the unicorn master process is also restarted and the correct assets were getting served.
Stopping and starting unicorn brings around 10 secs on downtime when compared to restarting the unicorn. This is the workaround that can be used where as long term solution is move to puma from unicorn.
참고URL : https://stackoverflow.com/questions/18700219/rails-4-assets-not-loading-in-production
'programing tip' 카테고리의 다른 글
Vim Regex 캡처 그룹 [bau-> byau : ceu-> cyeu] (0) | 2020.07.19 |
---|---|
Visual Studio 명령 프롬프트에서 PowerShell을 사용하려면 어떻게해야합니까? (0) | 2020.07.19 |
더 이상 사용되지 않는, 더 이상 사용되지 않는 및 더 이상 사용되지 않는 (0) | 2020.07.19 |
객체 속성으로 배열에서 객체 제거 (0) | 2020.07.19 |
Maven을 사용하여 릴리스 종속성을 강제로 다시 다운로드 (0) | 2020.07.19 |