I've got a ruby 2.4.0, rails 5.0.2, spree 3.2 app.
I tried to create a custom admin report for viewing all my inventory products. Ugly for now but works perfectly on development, unlike production where app crashes.
When running heroku run rails c it says You may have defined two routes with the same name using the:asoption, or you may be overriding a route already defined by a resource with the same naming.
Following, everything added after the last successful commit, by expected relevance:
routes.rb
Rails.application.routes.draw do
mount Spree::Core::Engine, at: '/'
MyApp::Application.routes.draw do
Spree::Core::Engine.routes.append do
get '/admin/reports/stock_per_location' => 'admin/reports#stock_per_location', as: 'stock_per_location_admin_reports'
end
end
end
production.rb
Rails.application.configure do
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
config.assets.js_compressor = :uglifier
config.assets.compile = true
config.log_level = :debug
config.log_tags = [ :request_id ]
config.action_mailer.perform_caching = false
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_formatter = ::Logger::Formatter.new
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end
config.active_record.dump_schema_after_migration = 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'),
url: ENV.fetch("BUCKET_URL"),
}
}
end
reports_controller_decorator.rb
require_dependency 'spree/admin/reports_controller'
Spree::Admin::ReportsController.class_eval do
add_available_report! :stock_per_location
def stock_per_location
#stock_locations = Spree::StockLocation.all
end
end
Aparently creating the routes directly isn't supported by the latest version of Spree, changed my routes.rb and it worked fine.
MyApp::Application.routes.draw do
Spree::Core::Engine.routes.append do
#causing troubles on production: get '/admin/reports/stock_per_location' => 'admin/reports#stock_per_location', as: 'stock_per_location_admin_reports', only: [:index]
namespace :admin do
resources :reports, only: [:index] do
collection do
get :stock_per_location
#post :total_sales_of_each_product
end
end
end
end
end
Related
I'm working on a project (Rails backend, React frontend) where I would like the user to receive an email when they register an account. I set up action-mailer with Gmail locally and it works fine Then when I deploy my backend to Heroku, it doesn't send the email or return a response to the frontend. Here it my development.rb file
require 'active_support/core_ext/integer/time'
Rails.application.configure do
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Print deprecation notices to the Rails logger.
config.active_support.deprecation = :log
# Raise exceptions for disallowed deprecations.
config.active_support.disallowed_deprecation = :raise
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
config.active_record.migration_error = :page_load
config.active_record.verbose_query_logs = true
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
domain: 'example.com',
user_name: ENV['GMAIL_USERNAME'],
password: ENV['GMAIL_PASSWORD'],
authentication: 'plain',
enable_starttls_auto: true
}
config.action_mailer.default_url_options = { host: 'localhost:3000' }
end
And my production.rb file looks like this :
require 'active_support/core_ext/integer/time'
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
# 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?
config.log_level = :info
# 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 = "Art_Wall_production"
# 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
# Log disallowed deprecations.
config.active_support.disallowed_deprecation = :log
# Tell Active Support which deprecation messages to disallow.
config.active_support.disallowed_deprecation_warnings = []
# 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
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.default_url_options = { host: 'art-wall-api.herokuapp.com', protocol: 'https' }
config.action_mailer.smtp_settings = {
address: 'smtp.gmail.com',
port: 587,
user_name: ENV['GMAIL_USERNAME'],
password: ENV['GMAIL_PASSWORD'],
authentication: 'plain',
enable_starttls_auto: true
}
end
This is where i'm calling the method "notify_user":
# post to db
def create
#user = User.new(user_params)
if #user.save
NewUserEmailMailer.notify_user(#user).deliver # call to mailer controller
#token = encode({ id: #user.id })
render json: {
user: #user.attributes.except('password_digest'),
token: #token
}, status: :created
else
# puts #user.errors.full_messages
render json: #user.errors, status: :unprocessable_entity
end
end
and here is the controller
class NewUserEmailMailer < ApplicationMailer
def notify_user(user)
#user = user
mail(to: #user.email, subject: 'Welcome to Art Wall')
end
end
Again, it works fine during development but when I deploy, it saves the user info in heroku db but then never sends the email OR returns a response to the frontend. Any help would be appreciated! Thanks
I'm building a Rails 6.0.3.4 backend, React.js frontend app and for some reason my session token is not saving on the production build after working perfectly fine on the development build. I've loosened restrictions on the production build on Heroku (in session_store.rb I tweaked it from requiring a specific domain to all domains). When I log in I have it return the session token data and it is there but it's not saving anything (tried multiple browsers/computers). On my react front end I do have {withCredentials: true} in my login/sign up components.
session_store.rb
if Rails.env.production?
Rails.application.config.session_store :cookie_store, key: '_10-athletes', domain: :all
else
Rails.application.config.session_store :cookie_store, key: '_10-athletes'
end
In my sessions_controller.rb
def create
#user = User.find_by(email: session_params[:usernameOrEmail])
unless #user
#user = User.find_by(username: session_params[:usernameOrEmail])
end
if #user && #user.authenticate(session_params[:password])
login!
render json: {
logged_in: true,
user: #user,#returns gthe user
session: session, #returns appropriate session info: session_id: 32 digit hex value, user_id: 1
production: Rails.env.production? #returns true, was curious if it was not registering properly
}
else
# working fine
}
end
end
def is_logged_in?
if logged_in? && current_user
# logged_in? is returning false, jumping to else
else
render json: {
session: session[:user_id], #returns null
}
end
end
application_controller.rb
def login!
session[:user_id] = #user.id
end
def logged_in?
!!session[:user_id]
end
config/application.rb
class Application < Rails::Application
config.load_defaults 6.0
config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore
config.middleware.insert_after(ActionDispatch::Cookies, ActionDispatch::Session::CookieStore)
end
config/environments/production.rb
Rails.application.configure do
config.cache_classes = true
config.eager_load = true
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present?
config.assets.compile = false
config.active_storage.service = :local
config.force_ssl = true # tested both including this line and not
config.api_only = false #tested both including this line and not
config.log_level = :debug
config.log_tags = [ :request_id ]
config.action_mailer.perform_caching = false
config.i18n.fallbacks = true
config.active_support.deprecation = :notify
config.log_formatter = ::Logger::Formatter.new
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
config.active_record.dump_schema_after_migration = false
end
Edit: Added in production.rb
Do you have secure cookies enabled as a option? With SSL?
I created a site for storing rails photo posts. Pictures are saved in AWS. Sites works fine - photos go to AWS and display on the site: https://pp-obrazkowo.herokuapp.com/pins
The problem is, entries are not showing up locally - http://127.0.0.1:3000/pins.
They will throw an error: missing required: bucket option
The site stopped working properly after configuring the paperclip service.
In addition, there is an error in the supervisor:
ArgumentError in Pins # index
Link to repository:
https://github.com/przemo88/obrazkowo
Code:
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 CSS using a preprocessor.
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# 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 = "Obrazkowo_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.default_url_options = { host: 'pp-obrazkowo.herokuapp.com' }
config.paperclip_defaults = {
:storage => :s3,
:s3_credentials => {
:bucket => ENV['S3_BUCKET_NAME'],
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
}
end
development.rb
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
# Show full error reports.
config.consider_all_requests_local = true
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join('tmp', 'caching-dev.txt').exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true
config.cache_store = :memory_store
config.public_file_server.headers = {
'Cache-Control' => "public, max-age=#{2.days.to_i}"
}
else
config.action_controller.perform_caching = false
config.cache_store = :null_store
end
# Store uploaded files on the local file system (see config/storage.yml for options).
config.active_storage.service = :local
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = false
config.action_mailer.perform_caching = false
# 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
# Highlight code that triggered database queries in logs.
config.active_record.verbose_query_logs = true
# 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
# Use an evented file watcher to asynchronously detect changes in source code,
# routes, locales, etc. This feature depends on the listen gem.
# config.file_watcher = ActiveSupport::EventedFileUpdateChecker
#
config.action_mailer.default_url_options = {host: 'localhost', port: 3000}
Paperclip.options[:command_path] = "/usr/local/bin/"
config.paperclip_defaults = {
:storage => :s3,
:s3_credentials => {
:bucket => ENV['S3_BUCKET_NAME'],
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
}
end
paperclip.rb
Paperclip::Attachment.default_options[:url] = ':s3_domain_url'
Paperclip::Attachment.default_options[:path] = '/:class/:attachment/:id_partition/:style/:filename'
Paperclip::Attachment.default_options[:s3_host_name] = 's3.us-east-2.amazonaws.com'
pins_controller.rb
class PinsController < ApplicationController
before_action :set_pin, only: [:show, :edit, :update, :destroy]
before_action :authenticate_user!, except: [:index, :show]
before_action :correct_user, only: [:edit, :update, :destroy]
# GET /pins
# GET /pins.json
def index
#pins = Pin.all
end
# GET /pins/1
# GET /pins/1.json
def show
end
# GET /pins/new
def new
#pin = current_user.pins.build
end
# GET /pins/1/edit
def edit
end
# POST /pins
# POST /pins.json
def create
#pin = current_user.pins.build(pin_params)
respond_to do |format|
if #pin.save
format.html { redirect_to #pin, notice: 'Pin was successfully created.' }
format.json { render :show, status: :created, location: #pin }
else
format.html { render :new }
format.json { render json: #pin.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /pins/1
# PATCH/PUT /pins/1.json
def update
respond_to do |format|
if #pin.update(pin_params)
format.html { redirect_to #pin, notice: 'Pin was successfully updated.' }
format.json { render :show, status: :ok, location: #pin }
else
format.html { render :edit }
format.json { render json: #pin.errors, status: :unprocessable_entity }
end
end
end
# DELETE /pins/1
# DELETE /pins/1.json
def destroy
#pin.destroy
respond_to do |format|
format.html { redirect_to pins_url, notice: 'Pin was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_pin
#pin = Pin.find(params[:id])
end
# Only allow a list of trusted parameters through.
def pin_params
params.require(:pin).permit(:description, :image)
end
def correct_user
#pin = current_user.pins.find_by(id: params[:id])
redirect_to pins_path, notice: "Nie jesteÅ› uprawniony do edycji tego pinu" if #pin.nil?
end
end
I think you may have made the same mistake I did before. In your development.rb file, do not edit the text to add your specific S3 keys. Just copy-paste the text directly as is listed in the tutorial.
#development.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']
}
}
Then, set the environmental variables AWS_BUCKET, AWS_ACCESS_KEY_ID, and AWS_SECRET_ACCESS_KEY as described by the author of the dev center article.
Btw, I'm not sure why you are using PaperClip(deprecated gem) on Rails 6. Rails 6 has ActiveStorage library to do the same thing perfectly.
I am up to Chapter 11.4 in Michael Hartl's Rails 5 book. Everything is green. However, I'm having trouble sending an activation email. Possible glitch between heroku and Cloud9? Keep in mind if I copy and paste the email the activation does work.
HEROKU LOGS:
INFO -- : [14c19bd6-0d0c-4f55-bc38-fc7330189513] Completed 500 Internal
Server Error in 710ms (ActiveRecord: 10.9ms)
2017-07-28T23:22:44.797443+00:00 app[web.1]: F, [2017-07-28T23:22:44.797379
#6] FATAL -- : [14c19bd6-0d0c-4f55-bc38-fc7330189513]
2017-07-28T23:22:44.797511+00:00 app[web.1]: F, [2017-07-28T23:22:44.797451
#6] FATAL -- : [14c19bd6-0d0c-4f55-bc38-fc7330189513] Errno::ECONNREFUSED
(Connection refused - connect(2) for "localhost" port 587):
2017-07-28T23:22:44.797572+00:00 app[web.1]: F, [2017-07-28T23:22:44.797514
#6] FATAL -- : [14c19bd6-0d0c-4f55-bc38-fc7330189513]
2017-07-28T23:22:44.797642+00:00 app[web.1]: F, [2017-07-28T23:22:44.797588
#6] FATAL -- : [14c19bd6-0d0c-4f55-bc38-fc7330189513]
app/models/user.rb:41:in `send_activation_email'
2017-07-28T23:22:44.797644+00:00 app[web.1]: [14c19bd6-0d0c-4f55-bc38-
fc7330189513] app/controllers/users_controller.rb:22:in `create'`enter code
here`
Production.rb:
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 = "sample_apps_#{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
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :smtp
host = 'infinite-plains-13710.herokuapp.com'
config.action_mailer.default_url_options = { host: host }
ActionMailer::Base.smtp_settings = {
:addresses => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'heroku.com',
:enable_starttls_auto => true
}
end
Part of the users_controller.rb file:
class UsersController < ApplicationController
before_action :logged_in_user, only: [:index, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :admin_user, only: :destroy
def index
#users = User.where(activated: true).paginate(page: params[:page])
end
def show
#user = User.find(params[:id])
redirect_to root_url and return unless #user.activated?
end
def new
#user = User.new
end
def create
#user = User.new(user_params)
if #user.save
#user.send_activation_email
flash[:info] = "Please check your email to account your account"
redirect_to root_url
else
render 'new'
end
end
development.rb:
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
# 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 = true
config.action_mailer.delivery_method = :test
host = 'rails-tutorial-dball1126.c9users.io' # Don't use this literally;
user your local dev host instead
config.action_mailer.default_url_options = { host: host, protocol: 'https' }
config.action_mailer.perform_caching = false
# 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
# Use an evented file watcher to asynchronously detect changes in source
code,
# routes, locales, etc. This feature depends on the listen gem.
config.file_watcher = ActiveSupport::EventedFileUpdateChecker
end
Your real error is in the logs:
(Connection refused - connect(2) for "localhost" port 587):
To use SMTP on Heroku, you'll need a "backing serivces" add-on for Heroku I think, according to their page here: https://devcenter.heroku.com/articles/smtp.
I am trying to upload locally using CarrierWave (for development). My file uploads and saves to
/public/uploads/news_page/hero_img/#{model.id}
However, when I try to call this image in the view I get this path:
No route matches [GET] "/uploads/news_page/hero_img/13/7388aa89cc3aef55b4de707420fcd1d7.jpeg"
But that IS where the image is and it is stored by that name in the database (just the image name). I don't know why it's showing a broken image in the view.
view.rb
figure
= image_tag #page.hero_img, alt: 'hero'
hero_img_uploader.rb
class HeroImgUploader < CarrierWave::Uploader::Base
include CarrierWave::RMagick
CarrierWave::SanitizedFile.sanitize_regexp = /[^[:word:]\.\-\+]/
# storage :fog
include CarrierWave::MimeTypes
process :set_content_type
storage :file unless Rails.env == "production"
# storage :fog unless Rails.env == "development"
# storage :fog unless Rails.env == "test"
# Override the directory where uploaded files will be stored.
# This is a sensible default for uploaders that are meant to be mounted:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
# def store_dir
# "pages/#{model.id}/hero/"
# end
# Process files as they are uploaded:
process :resize_to_limit => [1500, 500]
version :md do
process :resize_to_limit => [900, 300]
end
version :sm do
process :resize_to_limit => [420, 140]
end
# Add a white list of extensions which are allowed to be uploaded.
# For images you might use something like this:
def extension_white_list
%w(jpg jpeg gif png)
end
def filename
if original_filename
#name ||= Digest::MD5.hexdigest(File.dirname(current_path))
"#{#name}.#{file.extension}"
end
end
end
development.rb
Rails.application.configure do
# Settings specified here will take precedence over those in config/application.rb.
config.cache_classes = false
# Do not eager load code on boot.
config.eager_load = false
config.serve_static_files = false
config.assets.compile = true
# Show full error reports and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
config.action_mailer.raise_delivery_errors = false
config.active_support.deprecation = :log
config.active_record.migration_error = :page_load
# Debug mode disables concatenation and preprocessing of assets.
config.assets.debug = true
config.assets.digest = true
config.assets.raise_runtime_errors = true
# Configurations for MailCatcher
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = { :address => "localhost", :port => 1025 }
config.action_mailer.default_url_options = { host: 'localhost', port: 5000 }
CarrierWave.configure do |config|
config.storage = :file
end
end
relevant routes from "rake routes"
pages GET /pages(.:format) pages#index
POST pages(.:format) pages#create
new_page GET pages/new(.:format) pages#new
edit_page GET pages/:id/edit(.:format) pages#edit
page GET pages/:id(.:format) pages#show
PATCH pages/:id(.:format) pages#update
PUT pages/:id(.:format) pages#update
Case closed! Just change this line:
config.serve_static_files = false
To this one:
config.serve_static_files = true
In your config/development.rb file.
Probably you changed in unintentionally before (in production environment it makes sense because you have another server to serve assets, e.g. nginx or Apache).