Trying to use S3 to upload files via React on Rails - ruby-on-rails

so I'm following this article https://medium.com/#andrea.wayte/using-amazon-s3-to-store-images-for-react-on-rails-b1414ba2c0b2. Whenever I'm at the part where she migrates her database after updating the database I get this error.
admins-MBP:direct-s3-example admin$ rake db:migrate
rake aborted!
NameError: undefined local variable or method `config' for main:Object
/Users/admin/direct-s3-example/config/environments/development.rb:65:in `<main>'
/Users/admin/direct-s3-example/config/environment.rb:5:in `<main>'
Tasks: TOP => db:migrate => db:load_config => environment
(See full trace by running task with --trace)
I don't have an environment.rb file but here's my development.rb file.
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
end
Paperclip.options[:command_path] = "/usr/bin/"
config.paperclip_defaults = {
storage: :s3,
s3_host_name: 's3-us-east-2.amazonaws.com',
s3_credentials: {
bucket: ENV.fetch('petition-form'),
access_key_id: ENV.fetch('--------'),
secret_access_key: ENV.fetch('--------------'),
s3_region: ENV.fetch('us-east-2'),
}
}

The question has been answered. The code at the bottom was past the last end

Related

Setting up database for the first time in ruby on rails

I am very much fresh in using Ruby on rails. I have cloned a git repo and trying to set up a PostgreSQL database in my local machine(Win 10).
Ruby version- 2.4.10
Rails - 5.2.0
I am using the below command
rake db:setup RAILS_ENV=development
Error Output -
rake aborted!
NoMethodError: undefined method `[]' for nil:NilClass
D:/ruby/reserves/config/environments/development.rb:41:in `block in <top (required)>'
D:/ruby/reserves/config/environments/development.rb:1:in `<top (required)>'
D:/ruby/reserves/config/environment.rb:5:in `<top (required)>'
Tasks: TOP => db:setup => db:schema:load_if_ruby => db:create => db:load_config => environment
(See full trace by running task with --trace)
In database.yml file there are three environments has been declared - Development/Production/test
development:
<<: *default
database: reserves-dev
username:****
password:****
host: localhost
/config/environments/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.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
# Email
config.action_mailer.perform_caching = false
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.raise_delivery_errors = true
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
config.action_mailer.smtp_settings = {
address: Rails.application.credentials[Rails.env.to_sym][:mailer][:address],
port: Rails.application.credentials[Rails.env.to_sym][:mailer][:port],
user_name: Rails.application.credentials[Rails.env.to_sym][:mailer][:username],
password: Rails.application.credentials[Rails.env.to_sym][:mailer][:password],
domain: Rails.application.credentials[Rails.env.to_sym][:mailer][:domain],
authentication: :plain
}
# NOTE: For email need to have authentication :login (instead of :plain) and
# the tls: true param, otherwise the server times out on password reset request.
Rails.application.config.middleware.use ExceptionNotification::Rack,
:ignore_crawlers => %w{Googlebot bingbot},
:ignore_exceptions => ['ActionController::InvalidCrossOriginRequest'] + ExceptionNotifier.ignored_exceptions,
:email => {
:email_prefix => "[ERROR] ",
:sender_address => %{"Arc Reserves" <noreply#*****.com>},
:exception_recipients => %w{info#****.com}
}
# 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
end
How can I set the environment variable to development for setting the database in my local.
Any help is highly appreciated.
Thank you in advance.
Most likely this is because of the lines like:
Rails.application.credentials[Rails.env.to_sym][:mailer][:address]
Could you change it to something like that?
Rails.application.credentials.dig(:mailer, :address)

How to turn off Rails caching during development

I'm on Rails 5.2.2 and I'm building a web app that uses some static HTML, CSS, and JavaScript that I'm serving from inside of the public directory. Much of the time when I update a file it doesn't update in my browser when I refresh, but if I go into private browsing it works -- until it caches again and then I need to open a new private window.
How can I turn off caching for file in the public folder? Or if it's easier, how can I turn off all caching during development?
This is what my development.rb looks like. I tried commenting out the entire if Rails.root.join('tmp', 'caching-dev.txt').exist? block but that didn't do anything.
I'm also open to installing a gem to solve this if it can't be fixed with a setting.
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
config.file_watcher = ActiveSupport::FileUpdateChecker
# 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.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
# Add devide default mailer url
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# 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
It's not rails who caches, it's your browser.
Either you explicitly set
config.public_file_server.headers = {
'Cache-Control' => "no-cache"
}
(and clean your browser cache, who has all old and valid versions of your files), or you disable browser cache completely.

rails app not connecting to redis on heroku (RedisToGo)

am trying to push my rails 4 app on heroku but getting this error:
Error connecting to Redis on 127.0.0.1:6379 (ECONNREFUSED) (Redis::CannotConnectError)
on heroku logs, i have completed the RedisToGo setup as suggested by the heroku devcenter
but nothing happened i think am doing something wrong with RedisToGo URL
redis.rb
uri = URI.parse(ENV["REDIS_URL"] || "redis://redistogo:0deb5da103a95090a365444d016c59a6#angelfish.redistogo.com:9308/" )
$redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
my 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 and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Action Mailer configuration
config.action_mailer.raise_delivery_errors = true
config.action_mailer.delivery_method = :test
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
# 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
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
ENV["REDISTOGO_URL"] = 'redis://redistogo:0deb5da103a95090a365444d016c59a6#angelfish.redistogo.com:9308/'
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
# React configurations.
config.react.variant = :development
config.react.addons = true
config.after_initialize do
Bullet.enable = true
Bullet.alert = true
end
end

NameError: undefined local variable or method `config' for main:Object

New to Rails and had my app working just fine in production. However I recently updated the Heroku domain name and now I'm receiving the below error. I tried adding "config.assets.initialize_on_precompile = false" as recommended in some similar searches but this is not doing the trick. Any ideas on what is causing this?
Preparing app for Rails asset pipeline
remote: Running: rake assets:precompile
remote: rake aborted!
remote: NameError: undefined local variable or method `config' for main:Object
remote: /tmp/build_a19bfb10c80282a277c9ba26e985613b/config/environments/production.rb:95:in `<top (required)>'
remote: /tmp/build_a19bfb10c80282a277c9ba26e985613b/vendor/bundle/ruby/2.3.0/gems/activesupport-5.1.2/lib/active_support/dependencies.rb:292:in `require'
remote: /tmp/build_a19bfb10c80282a277c9ba26e985613b/vendor/bundle/ruby/2.3.0/gems/rake-12.0.0/exe/rake:27:in `<top (required)>'
remote: Tasks: TOP => environment
remote: (See full trace by running task with --trace)
remote: !
remote: ! Precompiling assets failed.
remote: !
remote: ! Push rejected, failed to compile Ruby app.
remote:
remote: ! Push failed
remote: Verifying deploy...
remote:
remote: ! Push rejected to myapp.
remote:
To https://git.heroku.com/mysite.git
! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/myapp.git'
Aaron:myapp2$
Here are my .rb files:
environment.rb
# Load the Rails application.
require_relative 'application'
# Initialize the Rails application.
Rails.application.initialize!
ActionMailer::Base.smtp_settings = {
:port => ENV['MAILGUN_SMTP_PORT'],
:address => ENV['MAILGUN_SMTP_SERVER'],
:user_name => ENV['MAILGUN_SMTP_LOGIN'],
:password => ENV['MAILGUN_SMTP_PASSWORD'],
:domain => 'myapp.herokuapp.com',
:authentication => :plain,
}
ActionMailer::Base.delivery_method = :smtp
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 Myapp2
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
config.assets.initialize_on_precompile = false
# 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.
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
config.assets.initialize_on_precompile = 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=#{2.days.seconds.to_i}"
}
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
# 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
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
config.assets.initialize_on_precompile = false
# Full error reports are disabled and caching is turned on.
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# 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 = 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
# 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 = "myapp2_#{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
end
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:port => ENV['MAILGUN_SMTP_PORT'],
:address => ENV['MAILGUN_SMTP_SERVER'],
:user_name => ENV['MAILGUN_SMTP_LOGIN'],
:password => ENV['MAILGUN_SMTP_PASSWORD'],
:domain => 'myapp.herokuapp.com', #mydomain actually contains the realvalue
:authentication => :plain,
}
In your production.rb, these:
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
# ...
}
should go inside the
Rails.application.configure do
# ...
end
block, as config is only available there.

Assets compiling on fly (Rails with compass gem)

I am trying to change my styles of my scss assets on my ruby on rails project but they are applying just after rake assets:precompile and restarting rails server.
With JS files everything allright and they are changing on fly.
Possible problem is with compass gem.
That is my repo - https://github.com/tanotify/blog
And file 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 and disable caching.
config.consider_all_requests_local = true
config.action_controller.perform_caching = false
# Don't care if the mailer can't send.
config.action_mailer.raise_delivery_errors = 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
# Asset digests allow you to set far-future HTTP expiration dates on all assets,
# yet still be able to expire them through the digest params.
config.assets.digest = true
# Adds additional error checking when serving assets at runtime.
# Checks for improperly declared sprockets dependencies.
# Raises helpful error messages.
config.assets.raise_runtime_errors = true
# Raises error for missing translations
# config.action_view.raise_on_missing_translations = true
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
end
Found solution! In config/environments/development.rb added line:
config.serve_static_assets = false

Resources