Devise Admin works locally but not on Heroku - ruby-on-rails

I'm creating an app using Ruby On Rails and Devise. I've created a User model and an Admin model and I have the app working fine when I run it locally but when I run it on heroku I'm having problems. The trouble is when I try to create a new admin I'm shown an error message that says "We're sorry, but something went wrong." I've already done a rake db:migrate and heroku run rake db:migrate. When I check heroku logs I see this:
2013-04-08T19:34:49+00:00 app[web.1]: Started GET "/admins/sign_up" for 98.154.183.5 at 2013-04-08 19:34:49 +0000
2013-04-08T19:34:49+00:00 app[web.1]: Processing by Admins::RegistrationsController#new as HTML
2013-04-08T19:34:50+00:00 app[web.1]: Rendered devise/registrations/new.html.erb within layouts/application (431.3ms)
2013-04-08T19:34:50+00:00 app[web.1]: ActionView::Template::Error (undefined method `name' for #<Admin:0x00000005207678>):
2013-04-08T19:34:50+00:00 app[web.1]: Completed 500 Internal Server Error in 549ms
2013-04-08T19:34:50+00:00 app[web.1]:
2013-04-08T19:34:50+00:00 app[web.1]: 3: <%= simple_form_for(resource, :as => resource_name, :url => registration_path(resource_name), :html => { class: 'form-horizontal'}) do |f| %>
2013-04-08T19:34:50+00:00 app[web.1]: 4: <%= f.error_notification %>
2013-04-08T19:34:50+00:00 app[web.1]: 5:
2013-04-08T19:34:50+00:00 app[web.1]: 6: <%= f.input :name %>
2013-04-08T19:34:50+00:00 app[web.1]: 8: <%= f.input :password %>
2013-04-08T19:34:50+00:00 app[web.1]: app/views/devise/registrations/new.html.erb:6:in `block in _app_views_devise_registrations_new_html_erb___3397140481100313441_30072880'
2013-04-08T19:34:50+00:00 app[web.1]: app/views/devise/registrations/new.html.erb:3:in `_app_views_devise_registrations_new_html_erb___3397140481100313441_30072880'
2013-04-08T19:34:50+00:00 app[web.1]: 7: <%= f.input :email %>
2013-04-08T19:34:50+00:00 app[web.1]: 9: <%= f.input :password_confirmation %>
2013-04-08T19:34:50+00:00 app[web.1]:
2013-04-08T19:34:50+00:00 app[web.1]:
2013-04-08T19:34:50+00:00 heroku[router]: at=info method=GET path=/admins/sign_up host=protected-cliffs-2228.herokuapp.com fwd="98.154.183.5" dyno=web.1 connect=1ms service=559ms status=500 bytes=643
For some reason unknown to me heroku is not linking to admins/registrations/new.html.erb but instead it's linking to devise/registrations/new.html.erb where it's reading the 'name' attribute that is showing up as an undefined method error.
My controllers/admins/registrations_controller.rb file looks like this:
class Admins::RegistrationsController < Devise::RegistrationsController
end
My routes.rb file looks like this:
MyFirstApp::Application.routes.draw do
get "users/show"
devise_for :admins, :controllers => { :registrations => "admins/registrations", :sessions => "admins/sessions" } do
get "/admins/sign_up" => "admins/registrations#new"
get "/admins/sign_in" => "admins/sessions#new"
end
resources :posts
devise_for :users
match 'users/:id' => 'users#show'
root :to => 'pages#home'
get 'about' => 'pages#about'
end
My development.rb file
MyFirstApp::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
# Log error messages when you accidentally call methods on nil.
config.whiny_nils = true
# 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
# Only use best-standards-support built into browsers
config.action_dispatch.best_standards_support = :builtin
# Raise exception on mass assignment protection for Active Record models
config.active_record.mass_assignment_sanitizer = :strict
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
config.active_record.auto_explain_threshold_in_seconds = 0.5
# Do not compress assets
config.assets.compress = false
# Expands the lines which load the assets
config.assets.debug = true
config.action_mailer.default_url_options = { :host => 'localhost:3000' }
end
My production.rb file
MyFirstApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
#In production, :host should be set to the actual host of your application.
config.action_mailer.default_url_options = { :host => 'myfirstapp.heroku.com' }
#Configuring Amazon S3 for Paperclip file uploads
config.paperclip_defaults = {
:storage => :s3,
:s3_credentials => {
:bucket => ENV['AWS_BUCKET'],
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
}
end
My .gitignore file
# See http://help.github.com/ignore-files/ for more about ignoring files.
#
# If you find yourself ignoring temporary files generated by your text editor
# or operating system, you probably want to add a global ignore instead:
# git config --global core.excludesfile ~/.gitignore_global
# Ignore bundler config
/.bundle
# Ignore the default SQLite database.
/db/*.sqlite3
# Ignore all logfiles and tempfiles.
/log/*.log
/tmp
doc/
*.swp
*~
.project
.DS_Store
.idea
# Ignore Paperclip unloaded files
/public/system
I'd appreciate any help I can get! This is my first time creating an app so I apologize if my question is dumb but I'm stuck and I need some help!

First check your gitrepo to make sure the file, or a related file, for some reason has been ignored.
And if that isn't the issue then just nuke the heroku project and start over.
Heroku has a special way of sometimes not creating new repos/projects correctly. The fail rate is pretty small, but you might have just rolled snake eyes.
If that doesn't work then post your production.rb and development.rb.

Related

Heroku/Rails App Error

I'm really stuck here and am worried my mailer config files are all messed up. My app seems to work fine locally, I'm on Nitrous. I can git push heroku master fine and when opened can view the home page, which is just a form(https://nameless-taiga-1654.herokuapp.com/), however once I hit submit I get an error message. I believe all my mailer actions on nitrous are setup correctly, I was planning on using sendgrid via heroku to run the mailing side of things. Basically I'm just lost and need help. Attached are the heroku logs of the form error.
heroku logs -t
2015-08-07T11:00:54.501756+00:00 heroku[router]: at=info method=POST path="/contacts" host=nameless-taiga-1654.herokuapp.com request_id=452df9b2-aef8-4a23-9ffb-3ba6781d80
75 fwd="124.149.33.78" dyno=web.1 connect=1ms service=72ms status=500 bytes=1754
2015-08-07T11:00:54.433019+00:00 app[web.1]: Started POST "/contacts" for 124.149.33.78 at 2015-08-07 11:00:54 +0000
2015-08-07T11:00:54.437794+00:00 app[web.1]: Parameters: {"utf8"=>"✓", "authenticity_token"=>"Z2Qh/GDIycId0uJk2evhblbKisGXNlIzjtz+xfJoyac=", "contact"=>{"name"=>"John D
oe", "phone"=>"040000000", "email"=>"johndoe#gmail.com", "event_type"=>"Corporate", "comments"=>"Test Comments"}, "commit"=>"Submit"}
2015-08-07T11:00:54.491841+00:00 app[web.1]:
2015-08-07T11:00:54.491846+00:00 app[web.1]: Sent mail to justindavidson23#gmail.com (21.8ms)
2015-08-07T11:00:54.491848+00:00 app[web.1]: Completed 500 Internal Server Error in 53ms
2015-08-07T11:00:54.492821+00:00 app[web.1]:
2015-08-07T11:00:54.492824+00:00 app[web.1]: Errno::ECONNREFUSED (Connection refused - connect(2)):
2015-08-07T11:00:54.436340+00:00 app[web.1]: Processing by ContactsController#create as HTML
2015-08-07T11:00:54.492826+00:00 app[web.1]: app/mailers/contact_mailer.rb:8:in `contact_email'
2015-08-07T11:00:54.463333+00:00 app[web.1]: Rendered contact_mailer/contact_email.html.erb (0.3ms)
2015-08-07T11:00:54.492828+00:00 app[web.1]: app/controllers/contacts_controller.rb:9:in `create'
2015-08-07T11:00:54.492831+00:00 app[web.1]:
2015-08-07T11:00:54.492830+00:00 app[web.1]:
2015-08-07T11:00:54.492827+00:00 app[web.1]: app/models/contact.rb:7:in `send_email'
contacts_controller.rb
class ContactsController < ApplicationController
def new
#contact = Contact.new
end
def create
#contact = Contact.new(contact_params)
if #contact.save
flash[:success] = 'Message Sent.'
redirect_to new_contact_path
else
flash[:danger] = 'Error occurred, messgage not sent.'
redirect_to new_contact_path
end
end
end
models/contact.rb
class Contact < ActiveRecord::Base
validates :name, :email, presence: true
after_create :send_email
private
def send_email
ContactMailer.contact_email(self).deliver
end
end
mailers/contact_mailer.rb
class ContactMailer < ActionMailer::Base
default to: 'justindavidson23#gmail.com'
def contact_email(contact)
#contact = contact
mail(from: #contact.email, subject: 'Contact Form Message').deliver
end
end
views/contact_mailer/contact_email.html.erb
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>New Message from Hoot and Holla's Contact form, from <%= "#{#contact.name}, #{#contact.email}" %></p>
<p><%= #contact.phone %></p>
<p><%= #contact.event_type %></p>
<p><%= #contact.comments %></p>
</body>
</html>
application.html.erb
<!DOCTYPE html>
<html>
<head>
<title>HootandhollaLp</title>
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body>
<div class="container">
<% flash.each do |key, value| %>
<div class="alert alert-<%= key %> alert-dismissible">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<%= value %>
</div>
<% end %>
<%= yield %>
</div>
</body>
</html>
#Pavan #alexsmn I hope this helps?
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
# Enable Rack::Cache to put a simple HTTP cache in front of your application
# Add `rack-cache` to your Gemfile before enabling this.
# For large-scale production use, consider using a caching reverse proxy like nginx, varnish or squid.
# config.action_dispatch.rack_cache = true
# Disable Rails's static asset server (Apache or nginx will already do this).
config.serve_static_assets = false
# Compress JavaScripts and CSS.
config.assets.js_compressor = :uglifier
# config.assets.css_compressor = :sass
# Do not fallback to assets pipeline if a precompiled asset is missed.
config.assets.compile = false
# Generate digests for assets URLs.
config.assets.digest = true
# Version of your assets, change this if you want to expire all your assets.
config.assets.version = '1.0'
# Specifies the header that your server uses for sending files.
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# Set to :debug to see everything in the log.
config.log_level = :info
# Prepend all log lines with the following tags.
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups.
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production.
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server.
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets.
# application.js, application.css, and all non-JS/CSS in app/assets folder are already added.
# config.assets.precompile += %w( search.js )
# 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
# Disable automatic flushing of the log to improve performance.
# config.autoflush_log = false
# Use default logging formatter so that PID and timestamp are not suppressed.
config.log_formatter = ::Logger::Formatter.new
# Do not dump schema after migrations.
config.active_record.dump_schema_after_migration = false
end
config/environment.rb
# Load the Rails application.
require File.expand_path('../application', __FILE__)
# Initialize the Rails application.
Rails.application.initialize!
ActionMailer::Base.smtp_settings = {
:address => 'smtp.sendgrid.net',
:port => '587',
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => 'heroku.com',
:enable_startstls_auto => true
}
I have had the same problem working with my current project. Actually, as I found out, this is a Gmail authentication problem. Your app is trying to login into Gmail account and cannot do it because Gmail does not see or recognize encrypted email and password. I temporarily solved this problem by writing necessary values into my smtp_settings directly, like:
smtp_settings = {
...
:user_name => "...your gmail email...",
:password => "...your gmail password...",
...
}
Also, I changed Gmail account security settings: turned off double authentication and allowed my account to be accessed by less secure apps. So, currently the app is deployed on Heroku and working. However, from cyber security point of view my solution is rather dangerous, so I am still looking for better ones.
EDITED!!!
There is a better way to encrypt gmail account settings. In my .bashrc file (is hidden in computer root directory - press Ctrl+H to reveal) I wrote the following lines of code:
export GMAIL_NAME=necessary value here
export GMAIL_PASSWORD=necessary value here
After this I also changed my smtp_settings one more time, like:
smtp_settings = {
...
user_name: ENV['GMAIL_NAME'],
password: ENV['GMAIL_PASSWORD'],
...
}
Finally, I configured repo setting on Heroku: Heroku/Personal apps/myApp/Settings, section "Config variables" via adding two new variables GMAIL_NAME and GMAIL_PASSWORD with necessary values.
It worked.
Try setting the following in your production.rb file:
config.action_mailer.delivery_method = :smtp
config.action_mailer.perform_deliveries = true
config.action_mailer.default_url_options = { host: 'nameless-taiga-1654.herokuapp.com' }
Also, to verify the configuration is correct, you can run heroku config.

image upload not working on heroku with s3

I'm using the Paperclip gem to handle image uploads on my Rails app. Everything works great in development but when I upload an image on the heroku app I get the "Something went wrong" error. I checked the heroku logs and I don't see any error messages. However, the one difference I noticed between dev and heroku is that the dev logs shows that the "begin..insert into...etc" SQL shows, whereas in heroku the logs don't show any SQL. It doesn't even get to write to the database.
The heroku logs only show the "Parameters" and some commands afterwards:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"****", "show"=>{"name"=>"test", "description"=>"this is a description", "cover"=>#<ActionDispatch::Http::UploadedFile:0x007f3776700fd0 #tempfile=#<Tempfile:/tmp/RackMultipart20140427-2-1431xte>, #original_filename="bc_top.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"show[cover]\"; filename=\"bc_top.png\"\r\nContent-Type: image/png\r\n">, "thumbnail"=>#<ActionDispatch::Http::UploadedFile:0x007f3776700eb8 #tempfile=#<Tempfile:/tmp/RackMultipart20140427-2-al452c>, #original_filename="bc_cover.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"show[thumbnail]\"; filename=\"bc_cover.png\"\r\nContent-Type: image/png\r\n">}, "commit"=>"Add show"}
Then it shows some other commands but no errors:
Command :: file -b --mime '/tmp/bdccc4601dd7e6aea5035c03817bca8020140427-2-2i17k4.png'
2014-04-27T16:06:34.040235+00:00 app[web.1]: Command :: file -b --mime '/tmp/68aaf40ebdc9b119d96bb0b3ff13118020140427-2-189rb23.png'
2014-04-27T16:06:34.150632+00:00 app[web.1]: Command :: file -b --mime '/tmp/bdccc4601dd7e6aea5035c03817bca8020140427-2-bfdlsj.png'
2014-04-27T16:06:33.966054+00:00 app[web.1]: vendor/bundle/ruby/2.1.0/gems/rack-1.5.2/lib/rack/handler/webrick.rb:60:in `service'
2014-04-27T16:06:33.966069+00:00 app[web.1]: Started POST "/shows" for 76.***.***.** at 2014-04-27 16:06:33 +0000
2014-04-27T16:06:33.966071+00:00 app[web.1]: Processing by ShowsController#create as HTML
2014-04-27T16:06:34.099317+00:00 app[web.1]: Command :: file -b --mime '/tmp/68aaf40ebdc9b119d96bb0b3ff13118020140427-2-5r5s9s.png'
2014-04-27T16:06:34.446474+00:00 heroku[router]: at=info method=POST path=/shows host=app.herokuapp.com request_id=1bc386a4-147c-403a-9b88-55fe488ec4e3 fwd="76.***.***.**" dyno=web.1 connect=2ms service=676ms status=500 bytes=919
I'm completely stumped. No errors! Here are the relevant files:
production.rb
appName::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
config.assets.precompile = [ /\A[^\/\\]+\.(ccs|js)$/i ]
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
# config/environments/production.rb
config.paperclip_defaults = {
:storage => :s3,
:s3_credentials => {
:bucket => ENV['AWS_BUCKET'],
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY']
}
}
end
application.rb
require File.expand_path('../boot', __FILE__)
require 'rails/all'
if defined?(Bundler)
# If you precompile assets before deploying to production, use this line
Bundler.require(*Rails.groups(:assets => %w(development test)))
# If you want your assets lazily compiled in production, use this line
# Bundler.require(:default, :assets, Rails.env)
end
module appName
class Application < Rails::Application
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
# Custom directories with classes and modules you want to be autoloadable.
# config.autoload_paths += %W(#{config.root}/extras)
# Only load the plugins named here, in the order given (default is alphabetical).
# :all can be used as a placeholder for all plugins not explicitly named.
# config.plugins = [ :exception_notification, :ssl_requirement, :all ]
# Activate observers that should always be running.
# config.active_record.observers = :cacher, :garbage_collector, :forum_observer
# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.
# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.
# config.time_zone = 'Central Time (US & Canada)'
# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.
# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]
# config.i18n.default_locale = :de
# Configure the default encoding used in templates for Ruby 1.9.
config.encoding = "utf-8"
# Configure sensitive parameters which will be filtered from the log file.
config.filter_parameters += [:password]
# Enable escaping HTML in JSON.
config.active_support.escape_html_entities_in_json = true
# Use SQL instead of Active Record's schema dumper when creating the database.
# This is necessary if your schema can't be completely dumped by the schema dumper,
# like if you have constraints or database-specific column types
# config.active_record.schema_format = :sql
# Enforce whitelist mode for mass assignment.
# This will create an empty whitelist of attributes available for mass-assignment for all models
# in your app. As such, your models will need to explicitly whitelist or blacklist accessible
# parameters by using an attr_accessible or attr_protected declaration.
config.active_record.whitelist_attributes = true
# Enable the asset pipeline
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.serve_static_assets = true
end
end
initializer/paperclip.rb
Paperclip::Attachment.default_options[:storage] = :s3
Paperclip::Attachment.default_options[:s3_protocol] = 'http'
Paperclip::Attachment.default_options[:s3_credentials] =
{ :bucket => ENV['AWS_BUCKET'],
:access_key_id => ENV['AWS_ACCESS_KEY_ID'],
:secret_access_key => ENV['AWS_SECRET_ACCESS_KEY'] }
Show model (object with the file attachments)
class Show < ActiveRecord::Base
has_many :episodes
has_attached_file :thumbnail
validates_attachment_content_type :thumbnail, :content_type => /\Aimage\/.*\Z/
has_attached_file :cover
validates_attachment_content_type :cover, :content_type => /\Aimage\/.*\Z/
end
I double checked my heroku config vars and they match up fine. I have this working on a different Rails 3 app and I'm wondering if I am missing something on this new Rails 4 app. Any ideas?
Thanks!
Heroku logs don't always help.
For your purposes since you're just getting started I would recommend setting your heroku app to "development" mode so you can see verbose error messages.
heroku config # Should return a list of your current environment, including RACK_ENV=production
heroku config:add RACK_ENV=development # now you'll get verbose error messages
heroku config:add RACK_ENV=production # set this back when you're done debugging
Check out the logs and tell us what you see.
But I would recommend that you use direct upload to S3. I've written about uploading images to S3 over here (http://blog.jobspire.net/uploading-images-to-heroku/). So do take a look.
Also Heroku has a read-only filesystem. That means Paperclip cannot save uploaded files to any place within Heroku. That might be the issue.
If you would like to be able to upload files to an application hosted
on Heroku, then you must either store the files as binary blobs within
your database or you must use a separate service to store the files.
If you are looking for a separate service, Paperclip has built-in
support for integrating with Amazon S3.
See the relevant Heroku docs.

Extra directory prepended to my routes in production

My rails application works fine locally, and seems to deploy normally. The root route brings you to my welcome splash page. I have a link on that page to the index for my organizations model, generated by the following code:
<%= link_to("Organizations", organizations_path, :class => "button_blue") %>
When I try to click that link on the production server, hosted by a2 hosting, I get the following error:
Started GET "/database/organizations.shtml" for 11.222.33.444 at Sat Oct 05 00:10:35 -0400 2013
ActionController::RoutingError (No route matches [GET] "/database/organizations.shtml"):
actionpack (3.2.13) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
...
Why is it trying to get "/database/organizations" instead of "/organizations" like it does in development? The url in the address bar reads "http://database.mysite.com/organizations". Does it have something to do with the fact that the site is located at the subdomain database.mysite.com? How do I get around this, since I can't use the primary domain for my rails app?
For what it's worth, here's what I get when I run
RAILS_ENV=production bundle exec rake routes | grep organization
on the server:
organizations GET /organizations(.:format) organizations#index
POST /organizations(.:format) organizations#create
new_organization GET /organizations/new(.:format) organizations#new
edit_organization GET /organizations/:id/edit(.:format) organizations#edit
organization GET /organizations/:id(.:format) organizations#show
PUT /organizations/:id(.:format) organizations#update
DELETE /organizations/:id(.:format) organizations#destroy
Here is my routes.rb:
MyApp::Application.routes.draw do
root :to => 'application#index'
resources :grantmakers, :grant_records, :events, :organizations
end
Here is my config/environments/production.rb:
MyApp::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to nil and saved in location specified by config.assets.prefix
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Prepend all log lines with the following tags
# config.log_tags = [ :subdomain, :uuid ]
# Use a different logger for distributed setups
# config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new)
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
# config.action_mailer.raise_delivery_errors = false
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Log the query plan for queries taking more than this (works
# with SQLite, MySQL, and PostgreSQL)
# config.active_record.auto_explain_threshold_in_seconds = 0.5
end
And here is my application_controller.rb:
class ApplicationController < ActionController::Base
protect_from_forgery
def index
end
before_filter :basic_http_authentication
private
def basic_http_authentication
if Rails.env.production?
authenticate_or_request_with_http_basic do |username, password|
username == '---' && password == '---'
end
end
end
end
Thanks very much for your help.
Thanks to #phoet, I finally identified the problem and found a solution.
My Apache server was rewriting the URLs for some reason that I still don't understand. I think it might have to do with the way A2 hosting allows you to set up subdomains. In any case, adding the following line to the end of the .htaccess file in the subdomain's root directory solved the problem:
RewriteEngine Off
This simply disables all rewriting: http://httpd.apache.org/docs/current/mod/mod_rewrite.html#rewriteengine

How to get asset caching working

I am trying to upgrade to cedar / asset pipeline and am stuggling with something.
Everything renders fine, but my app seems noticeably slower. Looking thorugh my logs I see tons of items like these:
2012-03-15T17:03:02+00:00 app[web.1]: cache: [GET
/assets/application.js] miss 2012-03-15T17:03:02+00:00 app[web.1]:
cache: [GET /assets/down_arrow.gif] miss 2012-03-15T17:03:02+00:00
app[web.1]: cache: [GET /assets/application.css] miss
I would expect these to be hits -- right?
My production.rb
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# For nginx:
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect'
# I also tried these
# config.action_dispatch.x_sendfile_header = "X-Sendfile"
# config.action_dispatch.x_sendfile_header = nil
config.cache_store = :dalli_store
My application.rb
...
config.assets.enabled = true
# Version of your assets, change this if you want to expire all your assets
config.assets.version = '1.0'
config.assets.initialize_on_precompile = false
config.active_support.deprecation = :log
Note: that assets:precompile works fine on deploy:
-----> Preparing app for Rails asset pipeline
Running: rake assets:precompile
-----> Rails plugin injection
Injecting rails_log_stdout
Injecting rails3_serve_static_assets
Thanks! Let me know if you need additional information
you probably missed one of the many asset-pipeline configurations. have a look at my production.rb file:
HamburgOnRuby::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Don't fallback to assets pipeline if a precompiled asset is missed
# config.assets.compile = false
# Generate digests for assets URLs
config.assets.digest = true
# Compress both stylesheets and JavaScripts
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :scss
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
# config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
config.action_dispatch.x_sendfile_header = nil # http://devcenter.heroku.com/articles/rails31_heroku_cedar#the_asset_pipeline
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
# config.log_level = :debug
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
# config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
# config.action_controller.asset_host = "http://assets.example.com"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
config.assets.precompile += %w( active_admin.js active_admin.css )
# Disable delivery errors, bad email addresses will be ignored
config.action_mailer.raise_delivery_errors = true
config.action_mailer.smtp_settings = {
:address => "smtp.sendgrid.net",
:port => "25",
:authentication => :plain,
:user_name => ENV['SENDGRID_USERNAME'],
:password => ENV['SENDGRID_PASSWORD'],
:domain => ENV['SENDGRID_DOMAIN']
}
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
# Set the default host for production
config.default_host = 'onruby.de'
end
I raised a support ticket with heroku and here was there response:
I'd give this a shot:
http://jackchu.com/blog/2011/09/20/rails-asset-pipeline-content-delivery-networks-and-rack-cache/
Recent investigations Rack::Cache and memcached/dalli seems to be
broken in Rails 3.1+.
That seemed to do the trick. I look forward to the interaction between Rack::Cache and dalli to be fixed, but in the mean time I will follow #jackchu approach

How can I use assets within Mailer?

I have trouble using any form of the asset pipeline within mailer, wether the Mailer itself or the view.
The following produces and empty src image tag.
<%= image_tag "emails/header-general.png" %>
The empty image tag looks like this:
img alt="Header-general"
The following form of attaching a file through the model and using it in the view attaches an empty image.
attachments.inline['header.jpg'] = 'emails/header-general.png'
...
<%= image_tag attachments['header.png'] %>
I did check the path and even tried with multiple paths and so on but with no luck.
Please help. Any form of including an image within the email would be helpful.
Here is the production env.
Xenium::Application.configure do
# Settings specified here will take precedence over those in config/application.rb
# Code is not reloaded between requests
config.cache_classes = true
# Full error reports are disabled and caching is turned on
config.consider_all_requests_local = false
config.action_controller.perform_caching = true
# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false
# Compress JavaScripts and CSS
config.assets.compress = true
# Choose the compressors to use
config.assets.js_compressor = :yui
config.assets.css_compressor = :yui
# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = true
# Generate digests for assets URLs
config.assets.digest = true
# Defaults to Rails.root.join("public/assets")
# config.assets.manifest = YOUR_PATH
# Specifies the header that your server uses for sending files
# config.action_dispatch.x_sendfile_header = "X-Sendfile" # for apache
config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for nginx
# Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies.
# config.force_ssl = true
# See everything in the log (default is :info)
config.log_level = :fatal
# Use a different logger for distributed setups
# config.logger = SyslogLogger.new
# Use a different cache store in production
config.cache_store = :mem_cache_store
# Enable serving of images, stylesheets, and JavaScripts from an asset server
#config.action_controller.asset_host = "http://asset.xenium.bg"
# Precompile additional assets (application.js, application.css, and all non-JS/CSS are already added)
# config.assets.precompile += %w( search.js )
# Disable delivery errors, bad email addresses will be ignored
config.action_mailer.raise_delivery_errors = true
#config.action_mailer.perform_deliveries = true
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => "localhost",
:port => 25,
:domain => 'xenium.bg',
#:user_name => '<username>',
#:password => '<password>',
#:authentication => 'plain',
:enable_starttls_auto => false
}
# Enable threaded mode
# config.threadsafe!
# Enable locale fallbacks for I18n (makes lookups for any locale fall back to
# the I18n.default_locale when a translation can not be found)
config.i18n.fallbacks = true
# Send deprecation notices to registered listeners
config.active_support.deprecation = :notify
end
Thanks!
set config.action_controller.asset_host and config.action_mailer.asset_host and this works well.
config.action_mailer.asset_host = URL from where pick image
<%= image_tag image_path('logo.png') %>
According to the 2.3.3 Making Inline Attachments section, to create an inline attachment you will do as follows
attachments.inline['image.jpg'] = File.read('/path/to/image.jpg')
So in your case, it should be
attachments.inline['header.jpg'] = File.read("#{Rails.root}/app/assets/images/emails/header-general.png"

Resources