I'm precompiling assets locally and pushing them to S3. In production I get this error:
heroku[router]: at=info method=GET path=/ host=www.someapp.org fwd="76.87.106.226" dyno=web.1 connect=2ms service=614ms status=500 bytes=0
app[web.1]: ActionView::Template::Error (couldn't find file 'bootstrap'
app[web.1]: app/views/application/_stylesheets.html.erb:1:in `...'
app[web.1]: app/views/layouts/application.html.erb:5:in `...'
app[web.1]:
app[web.1]: (in /app/app/assets/stylesheets/application.css:11)):
app[web.1]: 1: <%= stylesheet_link_tag "application", media: "all" %>
When I run in production mode locally I do not get that error.
Here is my application.rb:
require File.expand_path("../boot", __FILE__)
# Pick the frameworks you want:
require "active_record/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "active_resource/railtie"
require "sprockets/railtie"
# require "rails/test_unit/railtie"
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module SomeApp
class Application < Rails::Application
require "ksp"
require "markdowner"
require "patches/carrier_wave"
VERSION = "1.0.0"
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = "Central Time (US & Canada)"
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join("my", "locales", "*.{rb,yml}").to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record"s schema dumper when creating the database.
# This is necessary if your schema can"t be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = "1.0"
config.generators do |generator|
generator.test_framework :rspec, view_specs: false
end
config.assets.prefix = "/assets/#{Rails.env}"
config.filepicker_rails.api_key = ENV["FILEPICKER_API_KEY"]
# Allow for CORS requests
config.middleware.use Rack::Cors do
allow do
origins "*"
resource "*", headers: :any, methods: [:get, :post, :options]
end
end
end
end
Here is my production.rb:
SomeApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
config.cache_store = :dalli_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
config.action_controller.asset_host = "d20eprk8nbwd96.cloudfront.net"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
config.action_mailer.default_url_options = { host: "www.someapp.org" }
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
Here is my asset_sync.rb:
if defined?(AssetSync) && !(ENV["HOME"] == "/app")
AssetSync.configure do |config|
config.fog_provider = "AWS"
config.fog_directory = ENV["AMAZON_BUCKET"]
config.aws_access_key_id = ENV["AMAZON_S3_KEY"]
config.aws_secret_access_key = ENV["AMAZON_S3_SECRET"]
# Increase upload performance by configuring your region
config.fog_region = "us-west-2"
#
# Don't delete files from the store
config.existing_remote_files = ENV["ASSET_SYNC_EXISTING_REMOTE_FILES"]
#
# Automatically replace files with their equivalent gzip compressed version
config.gzip_compression = ENV["ASSET_SYNC_GZIP_COMPRESSION"]
#
# Use the Rails generated 'manifest.yml' file to produce the list of files to
# upload instead of searching the assets directory.
config.manifest = ENV["ASSET_SYNC_MANIFEST"]
#
# Fail silently. Useful for environments such as Heroku
# config.fail_silently = true
end
end
Here is my application.css:
/*
*= require bootstrap
*= require bootstrap-responsive
*= require font-awesome
*= require chosen
*= require bootstrap/tour
*= require bootstrap/lightbox
*= require_self
*/
In production mode locally the method gives me the correct cloudfront URL.
What's going wrong here?
Turns out despite precompiling locally, Heroku was still trying to precompile on Heroku.
It would fail, and then try to compile the assets live. This would then fail in the way described.
I solved this by creating an empty file /public/assets/manifest.yml, even though my config says assets are in /public/assets/production/
Related
I run a Rails 5.1.3 application on Pivotal Web Services. Since the upgrade from Rails 4 the application has the following behaviour:
deployment runs fine
puma starts
pivotal container is healthy
the first client that connects sits waiting for 2 to 3 minutes before being served the first page; during this period the server is using up to 100% CPU
This happens also when a new instance is being instantiated.
I have tried changing the 'eager loading' setting both true and false but no change in behaviour seen.
config.eager_load = true
I have tested with and without the rack-cors gem and also no changes.
Here is my config/application.rb:
require_relative 'boot'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
require 'pdfkit'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module MyFaro
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'Brussels'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
#config.i18n.load_path = Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :nl
#config.skylight.probes += %w(mongoid mongo)
config.middleware.use PDFKit::Middleware, {:print_media_type => true}, :only => %r[/print_story]
config.after_initialize do
ApplicationController.helpers.cache_set_look_up_hash
ApplicationController.helpers.cache_set_system_parameter_hash
end
end
end
and my config/environments/production.rb:
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
#CORS
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.cache_store = :memory_store
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
I am running Rails 5.1.3 with Puma on Pivotal Web Services. Since upgrading to this version from Rails 4, i am seeing the following errors appear in the logs:
1. ActionController::RoutingError (No route matches [GET] "/cloudfoundryapplication")
2. ActionController::RoutingError (No route matches [OPTION] "/cloudfoundryapplication")
I can't find any details on the "/cloudfoundryapplication" on Pivotal but as it an external application i figured it might be related to Cross-Origin Resource Sharing (CORS). I then used the 'rack-cors' gem to try to fix the issue. The effect was that the [OPTION] errors disappeared but not the [GET] errors.
Here is my config/application.rb:
require_relative 'boot'
require "rails"
# Pick the frameworks you want:
require "active_model/railtie"
require "active_job/railtie"
require "action_controller/railtie"
require "action_mailer/railtie"
require "action_view/railtie"
require "sprockets/railtie"
require "rails/test_unit/railtie"
require 'pdfkit'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module MyFaro
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
config.time_zone = 'Brussels'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
#config.i18n.load_path = Dir[Rails.root.join('config', 'locales', '*.{rb,yml}').to_s]
config.i18n.default_locale = :nl
#config.skylight.probes += %w(mongoid mongo)
config.middleware.use PDFKit::Middleware, {:print_media_type => true}, :only => %r[/print_story]
config.after_initialize do
ApplicationController.helpers.cache_set_look_up_hash
ApplicationController.helpers.cache_set_system_parameter_hash
end
end
end
and my config/environments/production.rb:
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
#CORS
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both threaded web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.cache_store = :memory_store
# Attempt to read encrypted secrets from `config/secrets.yml.enc`.
# Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or
# `config/secrets.yml.key`.
config.read_encrypted_secrets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
# `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = 'http://assets.example.com'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
# config.action_cable.url = 'wss://example.com/cable'
# config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ]
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
config.force_ssl = true
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :error
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Use a real queuing backend for Active Job (and separate queues per environment)
# config.active_job.queue_adapter = :resque
# config.active_job.queue_name_prefix = "my_faro_#{Rails.env}"
config.action_mailer.perform_caching = false
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { host: 'http://myfaro.cfapps.io/'}
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.mailgun.org',
port: 587,
authentication: 'plain',
#domain: 'sandboxe3e6f1cfc3d34efc8dba23c1a1eaff8b.mailgun.org',
domain: 'mg.myfaro.be',
#user_name: 'postmaster#sandboxe3e6f1cfc3d34efc8dba23c1a1eaff8b.mailgun.org',
user_name: 'postmaster#mg.myfaro.be',
#password: '25c695256391ca3e9f6c6bb1dd9f622f'
password: 'f1d6d58994362f084cc2ecac0e46256c'
}
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation cannot be found).
config.i18n.fallbacks = true
config.i18n.available_locales = [:en,:nl,:fr,:de]
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Use a different logger for distributed setups.
# require 'syslog/logger'
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
end
I got an answer from the Pivotal support team.
Pivotal Web Services' Apps Manager uses the /cloudfoundryapplication endpoint as the root for Spring Boot Actuator integrations. It calls this endpoint for an app when you view the app in the Apps Manager UI, regardless of whether you have configured Spring Boot Actuator endpoints for Apps Manager.
So for applications not using the Spring Boot Actuator endpoints these errors appear but only while using the Apps Manager GUI.
Its like Schrodingers Cat of the Light in the Fridge: if you don't look, the errors don't appear. I checked the logs via the CLI and indeed there are no errors at all.
Borrowing a line from an app's config/routes.rb:
match '/cloudfoundryapplication', to: proc { [200, {}, ['']] }, via: %i[get options]
I'm using the Paperclip gem to handle image uploads on my Rails app. Everything works great in development but when I upload an image on the heroku app I get the "Something went wrong" error. I checked the heroku logs and I don't see any error messages. However, the one difference I noticed between dev and heroku is that the dev logs shows that the "begin..insert into...etc" SQL shows, whereas in heroku the logs don't show any SQL. It doesn't even get to write to the database.
The heroku logs only show the "Parameters" and some commands afterwards:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"****", "show"=>{"name"=>"test", "description"=>"this is a description", "cover"=>#<ActionDispatch::Http::UploadedFile:0x007f3776700fd0 #tempfile=#<Tempfile:/tmp/RackMultipart20140427-2-1431xte>, #original_filename="bc_top.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"show[cover]\"; filename=\"bc_top.png\"\r\nContent-Type: image/png\r\n">, "thumbnail"=>#<ActionDispatch::Http::UploadedFile:0x007f3776700eb8 #tempfile=#<Tempfile:/tmp/RackMultipart20140427-2-al452c>, #original_filename="bc_cover.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"show[thumbnail]\"; filename=\"bc_cover.png\"\r\nContent-Type: image/png\r\n">}, "commit"=>"Add show"}
Then it shows some other commands but no errors:
Command :: file -b --mime '/tmp/bdccc4601dd7e6aea5035c03817bca8020140427-2-2i17k4.png'
2014-04-27T16:06:34.040235+00:00 app[web.1]: Command :: file -b --mime '/tmp/68aaf40ebdc9b119d96bb0b3ff13118020140427-2-189rb23.png'
2014-04-27T16:06:34.150632+00:00 app[web.1]: Command :: file -b --mime '/tmp/bdccc4601dd7e6aea5035c03817bca8020140427-2-bfdlsj.png'
2014-04-27T16:06:33.966054+00:00 app[web.1]: vendor/bundle/ruby/2.1.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb:60:in `service'
2014-04-27T16:06:33.966069+00:00 app[web.1]: Started POST "/shows" for 76.***.***.** at 2014-04-27 16:06:33 +0000
2014-04-27T16:06:33.966071+00:00 app[web.1]: Processing by ShowsController#create as HTML
2014-04-27T16:06:34.099317+00:00 app[web.1]: Command :: file -b --mime '/tmp/68aaf40ebdc9b119d96bb0b3ff13118020140427-2-5r5s9s.png'
2014-04-27T16:06:34.446474+00:00 heroku[router]: at=info method=POST path=/shows host=app.herokuapp.com request_id=1bc386a4-147c-403a-9b88-55fe488ec4e3 fwd="76.***.***.**" dyno=web.1 connect=2ms service=676ms status=500 bytes=919
I'm completely stumped. No errors! Here are the relevant files:
production.rb
appName::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
config.assets.precompile = [ /\A[^\/\\]+\.(ccs|js)$/i ]
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
# config/environments/production.rb
config.paperclip_defaults = {
:storage => :s3,
:s3_credentials => {
:bucket => ENV['AWS_BUCKET'],
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
}
end
application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module appName
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.serve_static_assets = true
end
end
initializer/paperclip.rb
Paperclip::Attachment.default_options[:storage] = :s3
Paperclip::Attachment.default_options[:s3_protocol] = 'http'
Paperclip::Attachment.default_options[:s3_credentials] =
{ :bucket => ENV['AWS_BUCKET'],
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'] }
Show model (object with the file attachments)
class Show < ActiveRecord::Base
has_many :episodes
has_attached_file :thumbnail
validates_attachment_content_type :thumbnail, :content_type => /\Aimage\/.*\Z/
has_attached_file :cover
validates_attachment_content_type :cover, :content_type => /\Aimage\/.*\Z/
end
I double checked my heroku config vars and they match up fine. I have this working on a different Rails 3 app and I'm wondering if I am missing something on this new Rails 4 app. Any ideas?
Thanks!
Heroku logs don't always help.
For your purposes since you're just getting started I would recommend setting your heroku app to "development" mode so you can see verbose error messages.
heroku config # Should return a list of your current environment, including RACK_ENV=production
heroku config:add RACK_ENV=development # now you'll get verbose error messages
heroku config:add RACK_ENV=production # set this back when you're done debugging
Check out the logs and tell us what you see.
But I would recommend that you use direct upload to S3. I've written about uploading images to S3 over here (http://blog.jobspire.net/uploading-images-to-heroku/). So do take a look.
Also Heroku has a read-only filesystem. That means Paperclip cannot save uploaded files to any place within Heroku. That might be the issue.
If you would like to be able to upload files to an application hosted
on Heroku, then you must either store the files as binary blobs within
your database or you must use a separate service to store the files.
If you are looking for a separate service, Paperclip has built-in
support for integrating with Amazon S3.
See the relevant Heroku docs.
Why Rails won't precompile a .js.erb asset?
My config/application.rb:
require File.expand_path('../boot', __FILE__)
require 'rails/all'
Bundler.require(:default, Rails.env)
module Sflitmap
class Application < Rails::Application
# these precompile OK
config.assets.precompile += ['edge/edge.1.5.0.min.js', 'edge/ink-falling_edgeActions.js', 'edge/inkAnimationTrigger.js']
# this will not precompile
config.assets.precompile += ['edge/ink-falling_edge.js.erb']
end
end
My config/environments/production.rb:
Sflitmap::Application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# Code is not reloaded between requests.
config.cache_classes = true
# Eager load code on boot. This eager loads most of Rails and
# your application in memory, allowing both thread web servers
# and those relying on copy on write to perform better.
# Rake tasks automatically ignore this option for performance.
config.eager_load = true
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
config.assets.paths << Rails.root.join('app', 'assets', 'fonts')
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
config.assets.precompile += %w( .svg .eot .woff .ttf )
# Ignore bad email addresses and do not raise email delivery errors.
# Set this to true and configure the email server for immediate delivery to raise delivery errors.
# config.action_mailer.raise_delivery_errors = false
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found).
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners.
config.active_support.deprecation = :notify
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
end
When I run RAILS_ENV=production rake assets:precompile I get:
- public
-- assets
--- edge
---- edge.1.5.0.min-610ab04bb1d4d0ad9a2a845821f04bdf.js
---- edge.1.5.0.min-610ab04bb1d4d0ad9a2a845821f04bdf.js.gz
---- ink-falling_edgeActions-9bdaa1845a29b15bd2562058432de721.js
---- ink-falling_edgeActions-9bdaa1845a29b15bd2562058432de721.js.gz
---- inkAnimationTrigger-3c35d0b73061bb5de0e691d694925902.js
---- inkAnimationTrigger-3c35d0b73061bb5de0e691d694925902.js.gz
Why won't ink-falling_edge-....js precompile?
I'm using ruby "2.0.0" and gem 'rails', '4.0.0'
This comment worked:
Why not try this line: config.assets.precompile +=
['edge/ink-falling_edge.js'] -> Rails may only reference files by
their (non ERB) asset filename - Rich Peck
I've got a rails app that's driving me crazy. I can't figure out why I'm getting duplicate js calls. I'm guessing it's something to do with the ordering or organization of the application.js require statements and the location of the .js files. I've also tried screwing around with production.rb and usually only make the .js completely broken with that. Here's what I've got:
app
|assets
||javascripts
|||+data_centers
|||-data_center.js
||-application.js
||-rails.js
vendor
|assets
||javascripts
||-autocomplete-rails.js
||-jquery-1.9.1.js
||-jquery-ui-1.10.2.custom.js
application.js has the following require statements:
//= require jquery-1.9.1
//= require jquery-ui-1.10.2.custom
//= require twitter/bootstrap
//= require bootstrap-typeahead
//= require rails
//= require autocomplete-rails
data_center.js has the following require statements:
//= require highcharts
//= require highcharts/modules/canvas-tools
//= require highcharts/modules/exporting
Before, I had the .js files from vendor/assets in app/assets but was advised to keep all external .js in the vendor/assets location. Point is that doesn't work.
My production.rb looks like this:
MyApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
#default false ^^
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = true
#defualt false
# Compress JavaScripts and CSS
config.assets.compress = false
#defualt true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
#default = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# config.assets.precompile += %w( jquery.js )
# config.assets.precompile += %w( jquery_ujs.js )
# config.assets.precompile += %w( jquery-ui-1.10.2.custom.js )
# config.assets.precompile += %w( twitter/bootstrap.js )
# config.assets.precompile += %w( bootstrap-typeahead.js )
# config.assets.precompile += %w( rails.js )
# config.assets.precompile += %w( autocomplete-rails.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
Please let me know if you have any ideas. Thanks.
You could try config.assets.debug = true in your production.rb to get a better picture, but I'd suggest first trying to debug problems with assets in development.
Some gems or their dependencies may be loading assets that you might not have been aware of.
In Rails console in the environment you are interested in (i.e. you might need to ssh to the server, etc. and/or set the environment in/before the command):
rails c
you might use the following to get a little more info from Sprockets about current assets:
Rails.application.assets.each_file {|path| begin; Rails.application.assets[path].dependencies.each{|d| puts "#{path} dependencies: /assets/#{d.logical_path}"}; rescue; puts "#{path}"; end}
Then you might look at gem list in your prod environment or look at Gemfile.lock to see what gems bundler is using. Maybe assets are being loaded that you didn't know about.
For asset organization, see the guide.
Also, consider that the guide suggests some different settings than what you are using in your production config, e.g. it suggests using config.assets.compress = true and to set config.serve_static_assets = false and have apache or nginx serve static assets, for performance reasons.