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
Related
So I'm new to Ruby on Rails. I've managed to get a basic website running, and I'm hosting it with Puma.
I'm trying to integrate websockets stuff, and was following this guide here:
https://guides.rubyonrails.org/action_cable_overview.html
My problem is that after implementing that, when I load my site, I still get an error in Chrome console:
"WebSocket connection to 'ws://:3000/cable' failed:"
There is no console output from ActionCable/Websockets whatsoever server-side. Nothing when I load the page, and nothing when I start the server.
At this point I feel like ActionCable wasn't installed correctly / is not running?
Just to reiterate, there is no console output at all from ActionCable server-side, even though the client is clearly trying to connect.
In routes.rb I have:
mount ActionCable.server => '/cable'
In development.rb I have:
config.action_cable.url = "ws://<website>:3000/cable"
config.action_cable.allowed_request_origins = [/http:\/\/*/, /https:\/\/*/]
config.action_cable.worker_pool_size = 5
config.action_cable.disable_request_forgery_protection = true
config.action_cable.mount_path = '/cable'
In app/channels/application_cable/connection.rb I have:
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :identity
def connect
puts "We got a connection!"
self.identity = find_verified_user
#self.identity = User.find_by(id: cookies.encrypted['_session']['user_id'])
end
private
def find_verified_user
puts "Finding verified user!"
session["didWebSocket"] = true #Needed to initialize session array?
session[:user_id]
end
end
end
I also just have my adapter set to async and have nothing else for my development environment in my cable.yml file.
So I have upgraded from rails 5.1 to 5.2
rails app:update
It all works well, and I instantly set up the active storage configuration to be used with a new section in the web application.
I created the migrations:
rails active_storage:install
rake db:migrate
I configured conf/storage.yml - production using AWS S3:
test:
service: Disk
root: <%= Rails.root.join("tmp/storage") %>
local:
service: Disk
root: <%= Rails.root.join("storage") %>
amazon:
service: S3
access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
region: eu-west-2
bucket: whatever
Adding the required GEM to GEMFILE:
gem 'aws-sdk-s3'
Making sure that Dev environment uses the local setup:
config.active_storage.service = :local
Adding all the required lines to the model:
class Article < ApplicationRecord
has_one_attached :main_picture
...
end
I did some fancy stuff, such as validation, custom variants, etc. - but for testing purposes and getting the basics working I commented out all that stuff.
Update Controller to use permitted attributes specified in Pundit:
Controller
#article.update(permitted_attributes(#article))
Pundit
class ArticlePolicy < ApplicationPolicy
...
def permitted_attributes
if !user.nil? && user.admin
[:title, :content, :teaser, :slug, :published, :user_id, :main_picture]
end
end
...
end
Now the upload works like a breeze - to my local environment and I even tested uploading it to AWS, but let's stick to the local environment. I can find the latest upload on the local environment in:
/storage/N1/Ay/N1AyNaBeMNGhhmPSR69XwA9a
And that is the URL when I try to display the image in my view:
http://localhost:3000/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBQQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--fd200a456532a80dfb122b2bdd9a53181b2a62aa/428KB.jpg
It appears like this in active_storage_blob table:
id,key,filename,content_type,metadata,byte_size,checksum,created_at
"55","N1AyNaBeMNGhhmPSR69XwA9a","428KB.jpg","image/jpeg","{""identified"":true,""width"":1920,""height"":1080,""analyzed"":true}","428299","48c8G3xQj5ENGgqqM08seQ==","2018-07-24 15:21:11"
Here is the various ways I tried to display the image:
= image_tag #article.main_picture
= image_tag url_for(#article.main_picture)
= image_tag #article.main_picture.variant(resize_to_fit: [100, 100]
None of these options displays the image that was successfully uploaded and stored in the DB. All I get is the image placeholder.
For the latest to work (but didn't) I added the following to the GEMFILE (as per guide):
gem 'image_processing', '~> 1.2'
There is a similar threat complaining about this - using Rails 5.1 and adding active_storage in the Gemfile - but there is no real answer. As suggested I tried adding:
config/application.rb
require 'active_storage/engine'
Didn't help displaying the image :(
--- UPDATE: The logs as requested when accessing the URL ---
Started GET "/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBQQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--fd200a456532a80dfb122b2bdd9a53181b2a62aa/428KB.jpg" for 127.0.0.1 at 2018-07-25 12:41:36 +0100
Processing by ActiveStorage::BlobsController#show as JPEG
Parameters: {"signed_id"=>"eyjfcmfpbhmionsibwvzc2fnzsi6ikjbahbqqt09iiwizxhwijpudwxslcjwdxiioijibg9ix2lkin19--fd200a456532a80dfb122b2bdd9a53181b2a62aa", "filename"=>"428kb"}
** [Localeapp] 1532518896 - Handling translation updates
** [Localeapp] 1532518896 - polling
** [Localeapp] API CALL: get https://api.localeapp.com/v1/projects/qXa7rByH1jQ9cNrU8t46zQkk8rkq3fMka13EACmQkXZ5FFTuUn/translations.yml?updated_at=1532518849
** [Localeapp] ATTEMPT 1
** [Localeapp] RESPONSE: 200
** [Localeapp] CALLING SUCCESS HANDLER: handle_success
** [Localeapp] 1532518897 - poll success
** [Localeapp] 1532518897 - reloading I18n
Filter chain halted as :set_blob rendered or redirected
Completed 404 Not Found in 917ms (ActiveRecord: 0.0ms)
Started GET "/rails/active_storage/blobs/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaHBQQT09IiwiZXhwIjpudWxsLCJwdXIiOiJibG9iX2lkIn19--fd200a456532a80dfb122b2bdd9a53181b2a62aa/428KB.jpg?disposition=attachment" for 127.0.0.1 at 2018-07-25 12:41:39 +0100
Processing by ActiveStorage::BlobsController#show as JPEG
Parameters: {"disposition"=>"attachment", "signed_id"=>"eyjfcmfpbhmionsibwvzc2fnzsi6ikjbahbqqt09iiwizxhwijpudwxslcjwdxiioijibg9ix2lkin19--fd200a456532a80dfb122b2bdd9a53181b2a62aa", "filename"=>"428kb"}
** [Localeapp] 1532518899 - Handling translation updates
** [Localeapp] 1532518899 - polling
** [Localeapp] API CALL: get https://api.localeapp.com/v1/projects/qXa7rByH1jQ9cNrU8t46zQkk8rkq3fMka13EACmQkXZ5FFTuUn/translations.yml?updated_at=1532518897
** [Localeapp] ATTEMPT 1
** [Localeapp] RESPONSE: 200
** [Localeapp] CALLING SUCCESS HANDLER: handle_success
** [Localeapp] 1532518900 - poll success
** [Localeapp] 1532518900 - reloading I18n
Filter chain halted as :set_blob rendered or redirected
Completed 404 Not Found in 837ms (ActiveRecord: 0.0ms)
NOTE:
I added an image download button to generate the log:
= link_to "Download", rails_blob_path(#article.main_picture, disposition: "attachment")
Your signed_id seems invalid, it is why you got a 'Filter chain halted as :set_blob rendered or redirected'.
Adding to the response:
The problem was caused by case-sensitive URLs. The GEM "route_downcaser" was installed. Upon removing this GEM everything worked as expected.
Also, "route_downcaser" offers the option of excluded_patterns. So you can use the GEM together with active_storage but make sure you add the following to the initializer:
# config/initializers/route_downcaser.rb
RouteDowncaser.configuration do |config|
config.redirect = true
config.exclude_patterns = [
/assets\//i,
/fonts\//i,
/active_storage\//i
]
end
More configuration options can be found here :)
Issue is with broadcasting data through a web socket using ActionCable. The error seems to suggest its coming from the create method.
Error Message
Rendered weight/_weight.html.erb (1.1ms)
[ActionCable] Broadcasting to weight: "<div class=\"row\">\n <div class=\"col-md-8 well\">\n <p>12.0 kg</p>\n <small>less than a minute</small>\n </div>\n</div>"
Completed 500 Internal Server Error in 25ms (Views: 7.4ms | ActiveRecord: 10.6ms)
NoMethodError (undefined method `fetch' for nil:NilClass):
app/controllers/weight_controller.rb:7:in `create'
Rendering /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb
Rendering /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_source.text.erb
Rendered /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_source.text.erb (0.8ms)
Rendering /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb
Rendered /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_trace.text.erb (0.9ms)
Rendering /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb
Rendered /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/_request_and_response.text.erb (1.1ms)
Rendered /usr/local/rvm/gems/ruby-2.3.4/gems/actionpack-5.0.4/lib/action_dispatch/middleware/templates/rescues/diagnostics.text.erb (25.0ms)
Create method from controller.rb
def create
#weight = Weight.new(weight_params)
#weight.user_id = current_user.id
if #weight.save
ActionCable.server.broadcast "weight", render(partial: 'weight/weight', object: #weight)
else
flash[:danger] = "New Weight was not added!"
redirect_to current_user
end
end
private
def weight_params
params.require(:weights).permit(:weight)
end
I just cant work out what is returned as nil. The fact that the info is correct in what it is broadcasting to weight is correct suggests it has saves it correctly to the database. Can't think what else it is performing the 'fetch' method on.
Pretty sure the web socket is set up correctly. See below.
config/application.rb :
config.action_cable.mount_path = '/cable'
config/routes.rb :
mount ActionCable.server => '/cable'
weight_channel.rb :
def subscribed
stream_from "weight"
end
weight.coffee :
received: (data) ->
$("#messages").prepend(data)
The error was raised due to a missing config/cable.yml file.
The solution was to use a config/cable.yml with the required setting for the application. i.e.:
# Action Cable uses Redis by default to administer connections, channels, and sending/receiving messages over the WebSocket.
production:
adapter: redis
url: redis://localhost:6379/1
development:
adapter: redis
url: redis://localhost:6379/1
staging:
adapter: redis
url: redis://localhost:6379/1
test:
adapter: async
The resolution appears in the question's comments.
Recently, I find out tagged logger. It is a very useful option and I config in production environment.
# config/environments/production.rb
...
config.log_tags = [ :uuid,:remote_ip ]
...
# log/production.log
[4d23e817-eca8-4db1-ba5b-7456d3af7f65] [127.0.0.1] Started GET "/resources/id" for 127.0.0.1 at 2015-11-26 21:09:11 +0900
I also want to print current login user name to log file, so I tried and found a link How to log user_name in Rails?.
But It's not working for me.
I'm using devise and rails4. How do I print?
Thanks in advance.
You can use a different approach. I've used the following one:
In application_controller.rb:
before_action: print_current_user
def print_current_user
if user_signed_in?
Rails.logger.debug "UserId: #{current_user.id}"
end
end
Or, you can use the lograge gem.
I'm troubleshooting my application to understand why emails fail through Rake.
My User model:
class User < ActiveRecord::Base
def User.test
puts "a string is returned"
UserMailer.email_test
end
end
My UserMailer:
class UserMailer < ActionMailer::Base
def email_test
mail to: "test", subject: "test"
end
end
If I call the method from the rails console (User.test) I obtain the correct output:
a string is returned
Rendered user_mailer/email_test.html.erb within layouts/mailer (0.8ms)
Rendered user_mailer/email_test.text.erb within layouts/mailer (0.2ms)
UserMailer#email_test: processed outbound mail in 106.5ms
=> #<Mail::Message:69873560567220, Multipart: true, <To: test>, <Subject: test>, <Mime-Version: 1.0>, <Content-Type: multipart/alternative; boundary="--==_mimepart_55c7b5db58f18_16fd3f8cb2e279986086"; charset=UTF-8>>
Now I am trying to move this in a rake task in a lib/tasks/scheduler.rake file as follows:
task :mytest => :environment do
User.test
end
When I call the task using
rake mytest
The only item I get returned is the string but nothing related to the email (see below).
bastien#bastien-ThinkPad-T540p:~/rails/app-505/lib/tasks$ rake mytest
(in /home/bastien/rails/app-505)
a string is returned
bastien#bastien-ThinkPad-T540p:~/rails/app-505/lib/tasks$
As far as I know, you don't get debug messages when running rake tasks, so the email is probably being generated successfully. The only problem I've found is that you're not using the deliver method in the generated email, so it's not being delivered. You need to run UserMailer.email_test.deliver to send it. To be sure that everything is working, I suggest that you install the letter_opener gem in the development environment, which opens up the email in a web browser tab.