i can't run properly actioncable on my ubuntu server, with docker
It seems to be a kind of authentification error with devise, this is my terminal log
There was an exception - NoMethodError(undefined method `user' for nil:NilClass)
cable_1 | /var/www/acim/public/app/channels/application_cable/connection.rb:17:in `find_verified_user'
This is my /app/chanels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
logger.add_tags 'ActionCable', current_user.email
end
protected
def find_verified_user
if (current_user = env['warden'].user)
#if current_user = User.find_by(id: cookies.signed[:user_id])
current_user
else
reject_unauthorized_connection
end
end
end
end
* And here the config/environemments/production.rb *
Rails.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 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 = true
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# 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
# `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
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
config.action_cable.url = 'ws://192.168.99.100/cable'
config.action_cable.allowed_request_origins = [ 'http://192.168.99.100', /http:\/\/192.168.99.100.*/, 'http://localhost' ]
#config.action_cable.url = [/ws:\/\/*/, /wss:\/\/*/]
#config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/]
# 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 = :debug
# 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 = "ACIM_#{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 = false
# 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
# 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
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# ne pas directement servir les fichiers public
# en utilisant ruby, mais passons par NGINX
config.public_file_server.enabled = false
config.assets.js_compressor = Uglifier.new(harmony: true)
end
Rails.application.config.assets.precompile += %w( *.js ^[^_]*.css *.css.erb )
Here my docker-compose.yml file
version: '3'
services:
db:
image: postgres:9.6
environment:
- ACIM_DATABASE_PASSWORD=ACIM_2018
volumes:
- 'db:/var/lib/postgresql/data'
env_file:
- '.env'
expose:
- '5432'
ports:
- "7000:5432"
nginx:
image: nginx:latest
container_name: production_nginx
volumes:
- ./config/nginx/nginx.conf:/etc/nginx/nginx.conf
- public-content:/var/www/acim/public
ports:
- 80:80
- 443:443
links:
- web
redis:
image: redis
command: redis-server
volumes:
- 'redis:/data'
ports:
- "6379"
sidekiq:
build: .
#command: sidekiq -C config/sidekiq.yml
command: bundle exec sidekiq
volumes:
- .:/ACIM
links:
- db
- redis
depends_on:
- db
- redis
env_file:
- '.env'
web:
build: .
# command: bundle exec rails s -p 3000 -b '0.0.0.0'
volumes:
- bundle_cache:/bundle
- public-content:/var/www/acim/public
- .:/ACIM
ports:
- "5000:3000"
depends_on:
- db
- redis
env_file:
- '.env'
cable:
depends_on:
- 'redis'
build: .
command: puma -p 28080 cable/config.ru
ports:
- '28080:28080'
volumes:
- '.:/ACIM'
env_file:
- '.env'
volumes:
bundle_cache:
redis:
db:
public-content:
Please help,
This is killing me since 2 days now !
Thanks in advance
I have a working setup using the warden cookie variant that you have commented plus a warden_hooks initializer to manage the creation and invalidation of the cookie
/app/chanels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
private
def find_verified_user
if current_user = User.find_by(id: cookies.signed['user_token'])
current_user.id
else
reject_unauthorized_connection
end
end
end
end
/app/config/initializers/warden_hooks.rb
# frozen_string_literal: true
# Set user_token cookie after sign in
Warden::Manager.after_set_user do |user, auth, opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}_token"] = user.id
end
# Invalidate user.id cookie on sign out
Warden::Manager.before_logout do |user, auth, opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}_token"] = nil
end
Finally i'm able to get everything working after some changes, so in case of it can help someone here is what worked for me:
/app/chanels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
# This is a websocket so we have no warden and no session here
# How to reuse the login made with devise?
# http://www.rubytutorial.io/actioncable-devise-authentication/
self.current_user = find_verified_user
logger.info("current_user: #{self.current_user.inspect}")
logger.add_tags "ActionCable", current_user.email
end
protected
def find_verified_user
verified_user = User.find_by(id: cookies.signed['user.id'])
if verified_user && cookies.signed['user.expires_at'] > Time.now
verified_user
else
reject_unauthorized_connection
end
end
end
end
/app/config/initializers/warden_hooks.rb
# http://www.rubytutorial.io/actioncable-devise-authentication/
Warden::Manager.after_set_user do |user,auth,opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}.id"] = user.id
auth.cookies.signed["#{scope}.expires_at"] = 30.minutes.from_now
end
Warden::Manager.before_logout do |user, auth, opts|
scope = opts[:scope]
auth.cookies.signed["#{scope}.id"] = nil
auth.cookies.signed["#{scope}.expires_at"] = nil
end
** config/environemments/production.rb**
Rails.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 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 = true
config.action_controller.perform_caching = true
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
# 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
# `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
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# Mount Action Cable outside main process or domain
# config.action_cable.mount_path = nil
#config.action_cable.url = 'ws://192.168.99.100/cable'
#config.action_cable.allowed_request_origins = [ 'http://192.168.99.100', /http:\/\/192.168.99.100.*/, 'http://localhost' ]
config.action_cable.url = 'ws://192.168.99.100/cable'
config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/]
# 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 = :debug
# 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 = "ACIM_#{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 = false
# 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
# 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
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# ne pas directement servir les fichiers public
# en utilisant ruby, mais passons par NGINX
config.public_file_server.enabled = false
config.assets.js_compressor = Uglifier.new(harmony: true)
end
Rails.application.config.assets.precompile += %w( *.js ^[^_]*.css *.css.erb )
config/initializers/sidekiq.yml
Sidekiq.configure_server do |config|
config.redis = { url: 'redis://192.168.99.100:6379' }
end
Sidekiq.configure_client do |config|
config.redis = { url: 'redis://192.168.99.100:6379' }
end
** Dockerfile **
FROM ruby:2.5.1
# Install dependencies
RUN apt-get update -qq && apt-get install -y build-essential libpq-dev nodejs
ENV RAILS_ROOT /var/www/acim/public
RUN mkdir -p $RAILS_ROOT
RUN mkdir -p $RAILS_ROOT/log
RUN rm -rf /var/www/acim/public/tmp/pids/server.pid
# Set working directory, where the commands will be ran:
WORKDIR $RAILS_ROOT
# Setting env up
ENV RAILS_ENV='production'
ENV RACK_ENV='production'
# Adding gems
COPY Gemfile Gemfile
COPY Gemfile.lock Gemfile.lock
RUN bundle install --jobs 20 --retry 5 --without development test
# Adding project files
COPY . .
RUN bundle exec rake assets:precompile
EXPOSE 3000
CMD ["bundle", "exec", "puma", "-C", "config/puma.rb"]
docker-compose.yml
version: '3'
services:
db:
image: postgres:9.6
environment:
- ACIM_DATABASE_PASSWORD=ACIM_2018
volumes:
- 'db:/var/lib/postgresql/data'
env_file:
- '.env'
expose:
- '5432'
ports:
- "7000:5432"
nginx:
image: nginx:latest
container_name: production_nginx
volumes:
- ./config/nginx/nginx.conf:/etc/nginx/nginx.conf
- public-content:/var/www/acim/public
ports:
- 80:80
- 443:443
links:
- web
# maildev:
# image: djfarrelly/maildev
# ports:
# - "2000:80"
redis:
image: redis
command: redis-server
volumes:
- 'redis:/data'
ports:
- "6379:6379"
sidekiq:
build: .
#command: sidekiq -C config/sidekiq.yml
command: bundle exec sidekiq
volumes:
- .:/ACIM
links:
- db
- redis
depends_on:
- db
- redis
env_file:
- '.env'
web:
build: .
volumes:
- bundle_cache:/bundle
- public-content:/var/www/acim/public
- .:/ACIM
ports:
- "5000:3000"
depends_on:
- db
- redis
env_file:
- '.env'
cable:
depends_on:
- 'redis'
- 'sidekiq'
build: .
command: puma -p 28080 cable/config.ru
ports:
- '28080:28080'
volumes:
- '.:/ACIM'
env_file:
- '.env'
volumes:
bundle_cache:
redis:
db:
public-content:
Related
I am using StimulusJS + Stimulus Reflex and it's all working on development. When I deploy to production (Digital Ocean) the connected() method is not fired.
The ReflexClass is performed and the ActiveRecord is updated on the server-side but the JS controller is not fired. this.stimulate() it's successfully fired because I can see the page is refreshed with new data.
Can you help me? I don't know where to look at.
I am using Cloudflare, Devise if it matters.
import { Controller } from 'stimulus'
import StimulusReflex from 'stimulus_reflex'
export default class extends Controller {
connect () {
StimulusReflex.register(this)
console.log("THIS IS CALLED ONLY ON DEVELOPMENT ENV")
}
}
view.html
<div data-controller="item-group" data-id="<%=item_group.id%>" >
<%= form.check_box :state,{id: "state-#{item_group.id}",
data: {reflex: 'change->ItemGroup#state', "reflex-dataset": 'combined'}}, 'enabled', 'paused' %>
</div>
head.html
<%= csrf_meta_tags %>
<%= csp_meta_tag %>
<%= action_cable_meta_tag %>
config/enviroment/production.rb
Rails.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 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
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
config.require_master_key = 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.new(harmony: true)
config.assets.css_compressor = :sass #
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# `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
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :amazon
# 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 = false
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# Prepend all log lines with the following tags.
config.log_tags = [ :request_id ]
# Use a different cache store in production.
#config.cache_store = :redis_cache_store, { url: ENV['REDIS_URL'] }
config.cache_store = :redis_cache_store, {driver: :hiredis, url: ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" }}
config.session_store :cache_store,
key: "_session",
compress: true,
pool_size: 5,
expire_after: 1.year
# 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 = "amazon_#{Rails.env}"
config.action_mailer.perform_caching = false
config.action_mailer.default_url_options = { host: 'example.com', :protocol => 'https', locale: 'en'}
config.action_controller.default_url_options = { host: 'example.com', :protocol => 'https', locale: 'en'}
config.action_mailer.asset_host = 'https://www.example.com'
# 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 cannot be found).
config.i18n.fallbacks = true
# 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
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Usato per Callback Advertisin Token (Url in model)
Rails.application.routes.default_url_options = config.action_mailer.default_url_options
end
config/cable.yml
development:
adapter: redis
url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
channel_prefix: development
test:
adapter: async
production:
adapter: redis
url: <%= ENV.fetch("REDIS_URL") { "redis://localhost:6379/1" } %>
channel_prefix: production
app/channels/application_cable/connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :session_id
def connect
self.session_id = cookies.encrypted[:session_id]
end
end
end
NGNIX (managed by Coud66)
{% if passenger_action_cable %}
location /cable {
passenger_app_group_name {{ app_name }}_action_cable;
passenger_force_max_concurrent_requests_per_process 0;
}
{% endif %}
I have a Rails 6 app that I'm trying to put in production but the css and js files can't be loaded.
I get the following error in the browser's console:
GET mydomain.com/packs/js/application-d0f5393dfb6f4a59c02e.js net::ERR_ABORTED 404
GET mydomain.com/packs/css/application-a03bb908.css net::ERR_ABORTED 404
Note that I don't have any errors in my log/production/log file.
config/environments/production.rb
Rails.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 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
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = true
config.serve_static_assets = true
# Disable serving static files from the `/public` folder by default since
# Apache or NGINX already handles this.
config.public_file_server.enabled = true
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=31536000",
}
# Compress CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = true
config.assets.digest = true
Rails.application.config.assets.precompile += %w( *.js ^[^_]*.css *.css.erb )
# 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
config.active_storage.service = :local_production
# 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 = false
# Use the lowest log level to ensure availability of diagnostic information
# when problems arise.
config.log_level = :debug
# 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 = "bounty_production"
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 = false
# 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
# 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
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
# Inserts middleware to perform automatic connection switching.
# The `database_selector` hash is used to pass options to the DatabaseSelector
# middleware. The `delay` is used to determine how long to wait after a write
# to send a subsequent read to the primary.
#
# The `database_resolver` class is used by the middleware to determine which
# database is appropriate to use based on the time delay.
#
# The `database_resolver_context` class is used by the middleware to set
# timestamps for the last write to the primary. The resolver uses the context
# class timestamps to determine how long to wait before reading from the
# replica.
#
# By default Rails will store a last write timestamp in the session. The
# DatabaseSelector middleware is designed as such you can define your own
# strategy for connection switching and pass that into the middleware through
# these configuration options.
# config.active_record.database_selector = { delay: 2.seconds }
# config.active_record.database_resolver = ActiveRecord::Middleware::DatabaseSelector::Resolver
# config.active_record.database_resolver_context = ActiveRecord::Middleware::DatabaseSelector::Resolver::Session
config.action_mailer.delivery_method = :postmark
config.action_mailer.postmark_settings = { api_token: Rails.application.credentials.postmark_api_token }
config.action_mailer.default_url_options = { host: "mydomain.com" }
end
config/webpacker.yml
# Note: You must restart bin/webpack-dev-server for changes to take effect
default: &default
source_path: app/javascript
source_entry_path: packs
public_root_path: public
public_output_path: packs
cache_path: tmp/cache/webpacker
check_yarn_integrity: false
webpack_compile_output: true
# Additional paths webpack should lookup modules
# ['app/assets', 'engine/foo/app/assets']
resolved_paths: []
# Reload manifest.json on all requests so we reload latest compiled packs
cache_manifest: false
# Extract and emit a css file
extract_css: true
static_assets_extensions:
- .jpg
- .jpeg
- .png
- .gif
- .tiff
- .ico
- .svg
- .eot
- .otf
- .ttf
- .woff
- .woff2
extensions:
- .erb
- .mjs
- .js
- .sass
- .scss
- .css
- .module.sass
- .module.scss
- .module.css
- .png
- .svg
- .gif
- .jpeg
- .jpg
development:
<<: *default
compile: true
# Verifies that correct packages and versions are installed by inspecting package.json, yarn.lock, and node_modules
check_yarn_integrity: true
# Reference: https://webpack.js.org/configuration/dev-server/
dev_server:
https: false
host: localhost
port: 3035
public: localhost:3035
hmr: false
# Inline should be set to true if using HMR
inline: true
overlay: true
compress: true
disable_host_check: true
use_local_ip: false
quiet: false
pretty: false
headers:
'Access-Control-Allow-Origin': '*'
watch_options:
ignored: '**/node_modules/**'
test:
<<: *default
compile: true
# Compile test packs to a separate directory
public_output_path: packs-test
production:
<<: *default
# Production depends on precompilation of packs prior to booting for performance.
compile: false
# Extract and emit a css file
extract_css: true
# Cache manifest.json for performance
cache_manifest: true
What I tried
I searched a lot of similar issues on stackoverflow and usually, the solution was to add
config.assets.compile = true
config.assets.digest = true
or
config.serve_static_assets = true
config.public_file_server.enabled = true
but it didn't change anything for me.
My assets are precompiled as I'm running rake assets:precompile --trace RAILS_ENV=production everytime before launching my server.
What is also really strange is that I have some pictures on my website that are loading correctly.
For example, mydomain.com/assets/main_picture-10fb4732e9edf8992cd02fb1425ef98ab13b0ce139d6df5299a41acf9093f0b3.png is working correctly. But, mydomain.com/packs/css/application-a03bb908.css returns an error telling me that this page doesn't exist.
And when I'm looking into my public folder (on my server):
ls public/packs/css
application-a03bb908.css application-a03bb908.css.br application-a03bb908.css.gz
So the file does exist but somehow my application can't access it.
Any clue on what I'm doing wrong here?
I was doing some changes in my app locally and everything was working fine, but after I deployed my app, the stylesheet files are not working. I already cloned the app to check if the files are present, and they are. So I imagine that the problem is in any of my config files.
How is:
How should be:
Here are my config files:
environments/production.rb
Rails.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 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
# Ensures that a master key has been made available in either ENV["RAILS_MASTER_KEY"]
# or in config/master.key. This key is used to decrypt credentials (and other encrypted files).
# config.require_master_key = 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 = false
# `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
# Store uploaded files on the local file system (see config/storage.yml for options)
config.active_storage.service = :local
# 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 = :debug
# 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 = "cronograma_capilar_#{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 = false
# 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
# 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
config.cache_classes = true
config.serve_static_assets = true
config.assets.compile = true
config.assets.digest = true
# 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
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
#config.web_console.whiny_requests = false
config.paperclip_defaults = {
storage: :s3,
s3_credentials: {
bucket: ENV.fetch('S3_BUCKET_NAME'),
access_key_id: ENV.fetch('AWS_ACCESS_KEY_ID'),
secret_access_key: ENV.fetch('AWS_SECRET_ACCESS_KEY')
},
s3_region: ENV.fetch('AWS_REGION')
}
Paperclip.options[:image_magick_path] = "/opt/ImageMagick/bin"
Paperclip.options[:command_path] = "/opt/ImageMagick/bin"
end
config/application.rb
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module CronogramaCapilar
class Application < Rails::Application
config.assets.initialize_on_precompile = false
config.assets.paths << "#{Rails}/vendor/assets/fonts"
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.2
# Settings in config/environments/* take precedence over those specified here.
# Application configuration can go into files in config/initializers
# -- all .rb files in that directory are automatically loaded after loading
# the framework and any gems in your application.
end
end
I also tried run the commands bundle exec rake assets:precompile, RAILS_ENV=production rake assets:precompile and not working :(
I have a strange issue on a rails app running on a docker container. I run RAILS_ENV=development db:drop db:create and it tries to create/drop only the test database.
Rails 5.0.0
my config/database.yml is
default: &default
adapter: postgresql
encoding: unicode
pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
development:
<<: *default
database: appname-api_development
username: appname
password: appname
host: <%= ENV['DOCKER_DB_HOST'] || 'localhost' %>
test:
<<: *default
database: appname-api_test<%= ENV['TEST_ENV_NUMBER'] %>
username: appname
password: appname
host: <%= ENV['DOCKER_DB_HOST'] || 'localhost' %>
and this is what I get:
root#9176b57db829:/appname# RAILS_ENV=development rake db:drop db:create
Dropped database 'db'
Dropped database 'appname-api_test'
Created database 'db'
Created database 'appname-api_test'
This is running on a docker container and there is no env set for RAILS_ENV or RACK_ENV or anything like that.
This is my docker-compose.yml:
version: '2'
services:
db:
image: postgres
restart: always
environment:
POSTGRES_USER: appname
POSTGRES_PASSWORD: appname
volumes:
- "${HOME}/.postgres-data:/var/lib/postgresql/data"
redis:
image: redis:3.2
api:
build: .
environment:
DOCKER_DB_HOST: 'db'
REDIS_PROVIDER: 'redis://redis:6379/1'
REDIS_URL: 'redis://redis:6379/1'
SMTP_HOST: 'localhost:3000'
# command: bundle exec rails s -b "0.0.0.0"
volumes:
- "${PWD}:/appname"
ports:
- "3000:3000"
- "4000:4000"
depends_on:
- db
- redis
networks:
default:
aliases:
- api
And this is my config/environments/development.rb file:
# frozen_string_literal: true
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# In the development environment your application's code is reloaded on
# every request. This slows down response time but is perfect for development
# since you don't have to restart the web server when you make code changes.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
config.action_cable.url = ENV["ACTIONCABLE_URL"]
config.action_cable.allowed_request_origins = [ ENV["FRONTEND_ORIGIN"] ]
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
if Rails.root.join("tmp/caching-dev.txt").exist?
config.action_controller.perform_caching = true
config.cache_store = :memory_store
config.public_file_server.headers = {
"Cache-Control" => "public, max-age=172800",
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
config.action_mailer.delivery_method = :letter_opener
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise an error on page load if there are pending migrations.
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
# This option may cause significant delays in view rendering with a large
# number of complex assets.
config.assets.debug = true
# Suppress logger output for asset requests.
config.assets.quiet = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# Uses Guard and LiveReload to reload html/css changes automatically
config.middleware.insert_after ActionDispatch::Static, Rack::LiveReload
end
Guys I am stuck at Timeout error on circleci.
Test cases are running fine on localhost but on circleci I get following error.
command bundle exec rspec took more than 10 minutes since last output
I have tried many changes but still my build fails due to TIMEOUT error.
I have also tried adding --format progress in bundle exec rspec command. but still same issue.
Here are my Configs for all file.
machine:
environment:
AWS_ACCESS_KEY_ID: key
AWS_SECRET_ACCESS_KEY: secret
AWS_REGION: us-east-1
TEST_CLUSTER_COMMAND: elasticsearch-1.5.2/bin/elasticsearch
TEST_CLUSTER_LOGS: /tmp
TEST_CLUSTER_NODES: 1
HOST: localhost:3000
QR_DOMAIN: test.bsqr1.com
ruby:
version: 2.3.1
hosts:
test.bsqr1.com: 127.0.0.1
dependencies:
bundler:
without: [development]
cache_directories:
- elasticsearch-1.5.2
post:
- if [[ ! -e elasticsearch-1.5.2 ]]; then wget https://download.elastic.co/elasticsearch/elasticsearch/elasticsearch-1.5.2.tar.gz && tar -xvf elasticsearch-1.5.2.tar.gz; fi
test:
override:
- bundle exec rspec:
parallel: true
Test.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
# The test environment is used exclusively to run your application's
# test suite. You never need to work with it otherwise. Remember that
# your test database is "scratch space" for the test suite and is wiped
# and recreated between test runs. Don't rely on the data there!
config.cache_classes = true
# Do not eager load code on boot. This avoids loading your whole application
# just for the purpose of running a single test. If you are using a tool that
# preloads Rails for running tests, you may have to set it to true.
config.eager_load = false
# Configure static file server for tests with Cache-Control for performance.
config.serve_static_files = true
config.static_cache_control = 'public, max-age=3600'
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Raise exceptions instead of rendering exception templates.
config.action_dispatch.show_exceptions = false
# Disable request forgery protection in test environment.
config.action_controller.allow_forgery_protection = false
# Tell Action Mailer not to deliver emails to the real world.
# The :test delivery method accumulates sent emails in the
# ActionMailer::Base.deliveries array.
config.action_mailer.delivery_method = :test
# Randomize the order test cases are executed.
config.active_support.test_order = :random
# Print deprecation notices to the stderr.
config.active_support.deprecation = :stderr
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
config.action_mailer.default_url_options = {host: 'localhost', port: 3000}
config.action_mailer.perform_deliveries = true
config.active_job.queue_adapter = :test
config.react.variant = :development
#sdm
config.assets.debug = true
config.assets.logger = Logger.new $stdout
config.assets.compress = true # Compress precompiled assets
config.assets.compile = false # Refuse to compile assets on-the-fly
config.assets.digest = true # Add a cache-busting extension to asset filenames
config.action_controller.asset_host = "file://#{::Rails.root}/public"
#sdm end
end
config.assets.debug = true
config.assets.logger = Logger.new $stdout
config.assets.compress = true # Compress precompiled assets
config.assets.compile = true # Refuse to compile assets on-the-fly
config.assets.digest = true # Add a cache-busting extension to asset filenames
config.action_controller.asset_host = "file://#{::Rails.root}/public"
I added this in my test.rb file there were also some style sheets issue.