I got a class AvatarUploader < Carrierwave::Uploader::Base which store User avatars in public/uploads dir:
def store_dir
"uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end
version :main do
process :resize_to_limit => [128, 128]
end
And I want to start application in production mode with assets precompilation enabled. Everything but avatars work fine. When I visit any User profile I get:
Started GET "/users/1" for 127.0.0.1 at 2012-05-03 17:45:24 +0300
Processing by Users::UsersController#show as HTML
Parameters: {"id"=>"1"}
Rendered users/users/show.html.erb within layouts/application (2.5ms)
Completed 500 Internal Server Error in 16ms
ActionView::Template::Error ( isn't precompiled):
87: <%= image_tag #user.avatar_url(:main).to_s %>
app/views/users/users/show.html.erb:87:in `_app_views_users_users_show_html_erb___538221278131396366_28399560'
Maybe there is a way to turn off precompilation for avatars(because they could be re-uploaded when app is running on production). Please provide any suggestions how to fix this issue. Thanks.
When image_tag receives a blank string, it tries to get a resource
from the asset pipeline and returns
"isn't precompiled"
https://github.com/rails/rails/issues/3080
Print #user.avatar_url(:main).to_s to double check
Related
I am simply trying to get rails to output to the console log. Here is what I have so far:
cable.yml
development:
adapter: redis
url: redis://localhost:6379/1
test:
adapter: redis
url: redis://localhost:6379/1
production:
adapter: redis
url: redis://localhost:6379/1
channel_prefix: enhanced_slack_ui_production
activity_channel.js
import consumer from "./consumer"
consumer.subscriptions.create("ActivityChannel", {
connected() {
console.log("testing");
},
disconnected() {
// Called when the subscription has been terminated by the server
},
received(data) {
// Called when there's incoming data on the websocket for this channel
}
});
activity_channel.rb
class ActivityChannel < ApplicationCable::Channel
def subscribed
stream_from "activity_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
I am on mac and ran brew install redis, added gem "redis" to the gem file under bootsnap.
Ran bundle install and bundle update. restarted both the redis server and rails server many times but when I visit my homepage (its local so can't share it) nothing shows up in the console. No errors just nothing.
The only setting I see in my development.rb file is: config.action_cable.disable_request_forgery_protection = true
Tried commenting that in and out, makes no difference.
Running rails 6.14
I checked several tutorials and the steps are always the same so I think my code is good but maybe I am missing something. If not how can I troubleshoot this to figure out why its not connection, any config files or settings that might block it or something like that?
I am trying to make my app update when it detects a push event from slack API so went with this approach, will consider alternative suggestions if there is no solution to this method.
Adding additional info:
I noticed on other videos when they startup their server there is a GET log releated to action cable and in the network tab they see cable as an entry. I have neither of those. This is all that shows on my logs after restarting the server.
[StatsD] EnhancedSlackUi.request_time:43|d|#controller:home,action:index,request_method:GET,request_format:text/html,response_code:200,response_type:2xx,environment:development
[StatsD] EnhancedSlackUi.request_time:3|d|#response_code:200,response_type:2xx,environment:development
Then I load the root page and it does show a message about the broadcast message. Nothing about the logging on activity_channel.js though.
Started GET "/" for 192.168.64.1 at 2021-07-24 10:03:05 +0100
Processing by HomeController#index as HTML
[ActionCable] Broadcasting to activity_channel: 2021-07-24 10:03:05.458896 +0100
[StatsD] company_metrics.client.redis.query_count:1|c|#namespace:project-name,environment:development
Rendering home/index.html.erb
ChannelPost Load (4.2ms) SELECT `channel_posts`.* FROM `channel_posts` WHERE `channel_posts`.`interaction_closed` = FALSE
↳ app/views/home/index.html.erb:254
ChannelPost Load (3.1ms) SELECT `channel_posts`.* FROM `channel_posts` WHERE `channel_posts`.`interaction_closed` = TRUE
↳ app/views/home/index.html.erb:271
ThreadMessage Load (3.5ms) SELECT `thread_messages`.* FROM `thread_messages` WHERE `thread_messages`.`thread_ts` = '1627075058.000200'
↳ app/views/home/index.html.erb:318
Rendered home/index.html.erb (Duration: 126.5ms | Allocations: 2820)
Completed 200 OK in 143ms (Views: 131.4ms | ActiveRecord: 16.1ms | Allocations: 3405)
My connection.rb file contents
# typed: strict
# frozen_string_literal: true
module ApplicationCable
class Connection < ActionCable::Connection::Base
end
end
My route file is here:
# typed: strict
# frozen_string_literal: true
Rails.application.routes.draw do
root "home#index"
get "home/index"
post "/events", to: "slack#events"
# For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
post "/graphql", to: "graphql#execute"
end
And my home controller is here:
# typed: true
# frozen_string_literal: true
require "date"
class HomeController < ApplicationController
def index
#open = ChannelPost.where(interaction_closed: 0)
#closed = ChannelPost.where(interaction_closed: 1)
#threads = ThreadMessage.where(thread_ts: "1627075058.000200")
ActionCable.server.broadcast('activity_channel', Time.now)
end
def format_date(date)
#new_date = date.strftime("%I:%M%p")
end
helper_method :format_date
end
The page I am trying to look for the broadcast message is on root which is home/index
One other thing, I am using a dev environment so instead of localhost I access the pages with a customized url i.e my_project_name.mycompany.com
In my hosts file I have this:
192.168.64.243 my_project_name.railgun
192.168.64.243 my_project_name.mycompany.com
I also see this in my hosts:
255.255.255.255 broadcasthost
127.0.0.1 localhost
::1 localhost
When I startup my server it shows:
Running /Users/mypath/project-name/bin/rails server -b 192.168.64.1 -p 53835 from dev.yml
* Listening on http://192.168.64.1:53835
Use Ctrl-C to stop
[warmup] Ready to accept requests: 0.0.0.0:8081
[asset server] Serving assets from:
• http://192.168.64.254:53835
Then further down:
[warmup] Destroyed all connections
[sewing-kit] Your app is accessible at https://project-name.companyname.com (Ctrl-T to open link in browser)
[warmup] Closed listener
[server] Running with latest changes
started react-server on 0.0.0.0:8081
Config Info
rails version 6.0
ruby version 2.7.0
gem 'image_processing', '~> 1.2'
storage.yml
local:
service: Disk
root: <%= Rails.root.join("storage") %>
development.rb
config.active_storage.service = :local
Rails.application.routes.default_url_options[:host] = 'localhost:3000'
config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }
This exception is coming only when I'm using service= :local. With AWS S3 config, on using :amazon it works fine.
user.rb model
has_one_attached :avatar
#throwing exception
def avatar_urls
{
original: avatar.service_url
} if avatar.attachment
end
While accessing avatar_urls the exception(URI::InvalidURIError (bad URI(is not URI?): nil) ) is thrown. However, as If I change my avatars_url method to following, it works fine.
#working method
def avatar_urls
{
thumbnail: url_for(avatar.variant(resize: "100x100").processed)
} if avatar.attachment
end
Here is the trace:
Disk Storage (5056.7ms) Generated URL for file at key: variants/i5w1ie6ro07mib4qcdn30lmik6wn/2a7fa5dad6ac227a16e961cbd12ca6f35f1d7947f56a97754d5e22c1a0fd3372 ()
cb_app_container | Completed 500 Internal Server Error in 9523ms (ActiveRecord: 580.9ms | Allocations: 1185509)
cb_app_container | URI::InvalidURIError (bad URI(is not URI?): nil):
cb_app_container | app/models/user.rb:53:in `avatar_urls'
cb_app_container | app/models/user.rb:27:in `user_json'
cb_app_container | app/controllers/api/v1/users_controller.rb:13:in `update'
cb_app_container | [ActiveJob] [ActiveStorage::AnalyzeJob] [33448db4-cf54-4677-906c-06b59f1579ee] (61.6ms) BEGIN
cb_app_container | [ActiveJob] [ActiveStorage::AnalyzeJob] [33448db4-cf54-4677-906c-06b59f1579ee] ActiveStorage::Blob Update (10.3ms) UPDATE "active_storage_blobs" SET "metadata" = $1 WHERE "active_storage_blobs"."id" = $2 [["metadata", "{\"identified\":true,\"width\":1952,\"height\":3264,\"analyzed\":true}"], ["id", 45]]
cb_app_container | [ActiveJob] [ActiveStorage::AnalyzeJob] [33448db4-cf54-4677-906c-06b59f1579ee] (19.6ms) COMMIT
cb_app_container | [ActiveJob] [ActiveStorage::AnalyzeJob] [33448db4-cf54-4677-906c-06b59f1579ee] Performed ActiveStorage::AnalyzeJob (Job ID: 33448db4-cf54-4677-906c-06b59f1579ee) from Async(default) in 6916.06ms
I ran into this same issue in Rails 6.1, and found that I had to include a special concern in my controller to make ActiveStorage aware of the current host:
module Api
module V1
class ApiController < ActionController::API
# Make ActiveStorage aware of the current host (used in url helpers)
include ActiveStorage::SetCurrent
end
end
end
I ended up including include Rails.application.routes.url_helpers in the controller and used rails_blob_url(avatar.image). I also aded this line in the routes file. I will refactor it later.
Rails.application.routes.default_url_options[:host] = 'localhost:3000'
I ended up using url_for:
Rails.application.routes.url_helpers.url_for(Event.last.image)
For anyone on Rails 5.x running into this issue, you need to define the host for the service_url. This is the code that ActiveStorage uses: https://github.com/rails/rails/blob/v5.2.6/activestorage/app/controllers/active_storage/base_controller.rb
The key line is: ActiveStorage::Current.host = request.base_url
Stick that before calling avatar.service_url
Big caveat: You probably don't want to be calling avatar.service_url directly. url_for(...) automatically deals with all this plumbing for you.
Simplest way for me was add this to application_controller.rb
# app/controllers/application_controller.rb
include ActiveStorage::SetCurrent
It's 100% from #RemonOldenbeuving's answer, just a little simpler.
According to the documentation https://api.rubyonrails.org/classes/ActiveStorage/Variant.html on processed.service_url: This will create and process a variant of the avatar blob that's constrained to a height and width of 100. Then it'll upload said variant to the service according to a derivative key of the blob and the transformations.
Also: https://api.rubyonrails.org/classes/ActiveStorage/Variant.html#method-i-service_url
Looking at the code at GH I can see the service comes from https://github.com/rails/rails/blob/fbe2433be6e052a1acac63c7faf287c52ed3c5ba/activestorage/app/models/active_storage/blob.rb which represents a web service, in this case S3.
I think (with the fear of being wrong and lose some points) that you shouldn't use it at local, only on prod as you said with S3. Seems like Disk is not considered as a service (for obvious reasons), have to dig more into the code (just dealing with this issue right now, it works if I set <%= image_tag category.image.variant(resize_to_fill: [400, 400]) %> but fails on <%= image_tag category.image.variant(resize_to_fill: [400, 400]).processed.service %>, on localhost, but I can access to .processed, is just .service that fails).
Did you do anything else to make it work on local? I guess you can also add a condition to check the env in which it's running.
better way to get the url is explained in this answer: https://stackoverflow.com/a/53547638
Rails.application.routes.url_helpers.rails_representation_url(picture_of_car.variant(resize: "300x300").processed, only_path: true)
I'm trying to add Searchkick to my Rails application. I'm following the exact instructions on the Get started page but I keep getting the following error:
Started GET "/airports" for 10.0.2.2 at 2014-05-26 10:20:33 +0000
Processing by AirportsController#index as HTML
Completed 500 Internal Server Error in 26ms
NameError (undefined local variable or method `searchkick' for #<Class:0xb48f3ba8>):
app/models/airport.rb:2:in `<class:Airport>'
app/models/airport.rb:1:in `<top (required)>'
app/controllers/airports_controller.rb:3:in `index'
Rendered /home/vagrant/.rvm/gems/ruby-2.1.1#global/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_source.erb (0.5ms)
Rendered /home/vagrant/.rvm/gems/ruby-2.1.1#global/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.2ms)
Rendered /home/vagrant/.rvm/gems/ruby-2.1.1#global/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (0.9ms)
Rendered /home/vagrant/.rvm/gems/ruby-2.1.1#global/gems/actionpack-4.1.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (19.8ms)
Here's what the Airport model looks like:
# ./app/models/airport.rb
class Airport < ActiveRecord::Base
searchkick
end
And this is what the Airport controller looks like:
# ./app/controllers/airports_controller/rb
class AirportsController < ApplicationController
def index
#airports = Airport.all
end
end
What's causing this?
Restart the server. The server has to be restarted after a change is made to the Gemfile.
Other things you can try if that doesn't work:
add gem 'searchkick' to the Gemfile
bundle install
Same here. I checked gem list, searchkick was there.
But I deleted searchkick in Gemfile and runned bundle install. Then add searchkick and bundle install again, it works well:)
I am attempting to code a very simple way for a user to add html files to my Heroku app. These files would be saved in ./log for rendering later. I have tested my code locally (in both development and production), but when I attempt to upload a file on my Heroku hosted repo I get internal server error 500.
controller upload.rb:
class UploadController < ApplicationController
def index
render :file => 'upload/uploadfile.haml'
end
def uploadFile
file_param = params[:upload][:datafile]
post = DataFile.save(file_param)
render :text => "File has been uploaded successfully"
end
end
model data_file.rb:
class DataFile < ActiveRecord::Base
def self.save(upload)
# Changed Default Destination: [__RAILS_DIR__/log]
name = "./log/" + upload.original_filename
# can haz data directory?
require 'FileUtils'
FileUtils.mkdir_p(File.dirname(name))
File.open(name, "wb") { |f| f.write(upload.read) }
end
end
view uploadfile.haml:
%h1 File Upload
= form_for :upload,:url=>{:action => 'uploadFile'},:html => { :multipart => true } do |f|
%p
%label{:for => "upload_file"} Select File
\:
\#{f.file_field 'datafile'}
= f.submit "Upload"
heroku logs:
2012-08-07T14:13:20+00:00 app[web.1]: Started POST "/uploadFile" for 69.29.117.99 at 2012-08-07 14:13:20 +0000
2012-08-07T14:13:20+00:00 app[web.1]: Processing by UploadController#uploadFile as HTML
2012-08-07T14:13:20+00:00 app[web.1]: Parameters: {"utf8"=>"✓", "authenticity_token"=>"1dAXkMulNR0d8S/l6QC8JnpSDtNBaHoyKJezgnheR10=", "upload"=>{"datafile"=>#>}, "commit"=>"Upload"}
2012-08-07T14:13:20+00:00 app[web.1]: Completed 500 Internal Server Error in 3ms
2012-08-07T14:13:20+00:00 app[web.1]:
2012-08-07T14:13:20+00:00 app[web.1]: LoadError (no such file to load -- FileUtils):
2012-08-07T14:13:20+00:00 app[web.1]: app/models/data_file.rb:7:in save'
2012-08-07T14:13:20+00:00 app[web.1]: app/controllers/upload_controller.rb:8:inuploadFile'
2012-08-07T14:13:20+00:00 app[web.1]:
2012-08-07T14:13:20+00:00 app[web.1]:
2012-08-07T14:13:20+00:00 app[web.1]: cache: [POST /uploadFile] invalidate, pass
heroku: http://upload-example.herokuapp.com/
github: https://github.com/halterj1/upload
Please no trying to convince me to use paperclip or carrierwave, that does not answer my question. Any help would be greatly appreciated, thanks in advance guys!
You should read this article on heroku: https://devcenter.heroku.com/articles/read-only-filesystem
edit:
As stated in article.
Your app is compiled into a slug for fast distribution across the dyno manifold. The filesystem for the slug is read-only, which means you cannot dynamically write to the filesystem for semi-permanent storage. The following types of behaviors are not supported:
Caching pages in the public directory
Saving uploaded assets to local disk (e.g. with attachment_fu or paperclip)
Writing full-text indexes with Ferret
Writing to a filesystem database like SQLite or GDBM
Accessing a git repo for an app like git-wiki
There are two directories that are writeable: ./tmp and ./log (under your application root). If you wish to drop a file temporarily for the duration of the request, you can write to a filename like #{RAILS_ROOT}/tmp/myfile_#{Process.pid}. There is no guarantee that this file will be there on subsequent requests (although it might be), so this should not be used for any kind of permanent storage.
I've just completed my user photo album feature in my application and images upload to public/uploads folder, but he images aren't showing and this is coming up in my logs:
Started GET "/uploads/photo/image/11/thumb_admguk.png" for 127.0.0.1 at 2012-01-19 00:42:26 +0000
ActionController::RoutingError (No route matches [GET] "/uploads/photo/image/11/thumb_admguk.png"):
Would very much appreciate help figuring out this issue.
Kind regards
This caused my issue:
config.serve_static_assets = false
This was my solution:
config.serve_static_assets = true
If you use Paperclip, try to add this in your Model:
has_attached_file :your_attribute_name,
:url => "/uploads/photo/image/:id/:basename.:extension",
:path => ":rails_root/public/uploads/photo/image/:id/:basename.:extension"
...