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.
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
I built an app with Facebook login function by Rails which perfectly worked on localhost, but now it doesn't work on Heroku. It looks like a common problem everyone gets, but none of the past questions or other articles helped.
error image
The above link goes to the error image. It should be coming from Heroku but Facebook because I saw the same error when I was dealing with Stripe. Before this error started bothering me, there was another error from Facebook saying Can't Load URL: The domain of this URL isn't included in the app's domains. To be able to load this URL, add all domains and subdomains of your app to the App Domains field in your app settings. but it was solved by adding the Heroku url to the Facebook app page.
I did figaro heroku:set -e production so the app keys and secrets mush have been set in Heroku.
Here are some codes from my files;
config/initializers/devise.rb
config.omniauth :facebook, ENV["facebook_app_id"], ENV["facebook_app_secret"], scope: 'email', info_fields: 'email,name', secure_image_url: true
app/models/user.rb
def self.from_omniauth(auth)
where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
user.email = auth.info.email
user.password = Devise.friendly_token[0,20]
user.name = auth.info.name # assuming the user model has a name
user.image = "http://graph.facebook.com/#{auth.uid}/picture?type=large" # assuming the user model has an image
# If you are using confirmable and the provider(s) you use validate emails,
# uncomment the line below to skip the confirmation emails.
# user.skip_confirmation!
end
end
controllers/users/omniauth_callback_controller.rb
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
def facebook
# You need to implement the method below in your model (e.g. app/models/user.rb)
#user = User.from_omniauth(request.env["omniauth.auth"])
if #user.persisted?
sign_in_and_redirect #user, :event => :authentication #this will throw if #user is not activated
set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
else
session["devise.facebook_data"] = request.env["omniauth.auth"]
redirect_to new_user_registration_url
end
end
def failure
redirect_to root_path
end
end
heroku logs
2017-07-17T15:33:54.234171+00:00 app[web.1]: Started GET "/users/auth/facebook/callback?code=AQCoKbzr4 ///// 00703" for 150.116.22.144 at 2017-07-17 15:33:54 +0000
2017-07-17T15:33:54.236011+00:00 app[web.1]: I, [2017-07-17T15:33:54.235951 #4] INFO -- omniauth: (facebook) Callback phase initiated.
2017-07-17T15:33:54.360053+00:00 app[web.1]: Processing by Users::OmniauthCallbacksController#facebook as HTML
2017-07-17T15:33:54.360097+00:00 app[web.1]: Parameters: {"code"=>"AQCoKbzr4nv6c7BEpM ///// 86c27a00703"}
2017-07-17T15:33:54.371557+00:00 app[web.1]: User Load (1.8ms) SELECT "users".* FROM "users" WHERE "users"."provider" = $1 AND "users"."uid" = $2 ORDER BY "users"."id" ASC LIMIT 1 [["provider", "facebook"], ["uid", "102081518247"]]
2017-07-17T15:33:54.581790+00:00 heroku[router]: at=info method=GET path="/users/auth/facebook/callback?code=AQCoK ///// a00703" host=xxxxxxx-xxxx-xxxxx.herokuapp.com request_id=93945-1199-417e-8d98-ede264cb fwd="150.116.22.144" dyno=web.1 connect=1ms service=350ms status=500 bytes=1754 protocol=https
2017-07-17T15:33:54.578410+00:00 app[web.1]: Completed 500 Internal Server Error in 218ms (ActiveRecord: 3.0ms)
2017-07-17T15:33:54.579175+00:00 app[web.1]:
2017-07-17T15:33:54.579178+00:00 app[web.1]: RuntimeError (redirection forbidden: http://graph.facebook.com/102087018247/picture?type=large -> https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/13064_10202475740292_410664266178542_n.jpg?oh=ef118e9d947604c9c7055a92e2&oe=5A02F8B4):
2017-07-17T15:33:54.579178+00:00 app[web.1]: app/models/user.rb:18:in `block in from_omniauth'
2017-07-17T15:33:54.579179+00:00 app[web.1]: app/models/user.rb:14:in `from_omniauth'
2017-07-17T15:33:54.579180+00:00 app[web.1]: app/controllers/users/omniauth_callbacks_controller.rb:4:in `facebook'
2017-07-17T15:33:54.579180+00:00 app[web.1]:
2017-07-17T15:33:54.579181+00:00 app[web.1]:
I have no idea what RuntimeError from the Heroku logs indicates... Any clue or advice would be appreciated.
You got redirection error because the image url will redirect user to another url. and there is a limitation in the open-uri when redirect http to https.
In the error message you can see this url: http://graph.facebook.com/102087018247/picture?type=large will be redirected to https://scontent.xx.fbcdn.net/v/t1.0-1/p200x200/13064_10202475740292_410664266178542_n.jpg?oh=ef118e9d947604c9c7055a92e2&oe=5A02F8B4
you can work around this issue by replacing http with https in your image url
"https://graph.facebook.com/#{auth.uid}/picture?type=large"
or using this way:
user.remote_image_url = auth.info.image.gsub(/\Ahttp:/, "https")
mMake sure you have whitelisted the production applications domain in Facebook Developers Console.
I usually set up a sub test app from my default app, test app has its own keys and set up ENV for them and localhost is whitelisted. This way development is easier
Then have ENV set for production app inside your App and Heroku, with Heroku domain whitelisted. Make sure your callback contains the Heroku production domain, matching the one you whitelisted
Then migrating Heroku database after the push to Heroku (this one works often for me)
heroku run rake db:migrate
Btw the way your accessing the image is different that how i've done it.
user.remote_avatar_url = auth.info.image
if this doesn't work, tell me, i've set up a few Facebook login on Heroku in my time.
When i performance a search with Yourub gem configuration for a youtube video search, the server console returns me the following error message:
Completed 500 Internal Server Error in 7ms
NameError (uninitialized constant ExploreController::Yourub):
app/controllers/explore_controller.rb:18:in `search'
Added config/yourub.yml as showed on the gem site
https://github.com/edap/yourub
On the explore_controller file we can find this:
class ExploreController < ApplicationController
def index
...
end
def search
if params[:queryType] == "users"
...
elsif params[:queryType] == "tracks"
client = Yourub::Client.new
client.search(query: params[:queryField]) do |v|
puts v
end
return redirect_to('/explore')
else
return redirect_to('/explore')
end
end
end
Also added my yourub.yml file here:
yourub_defaults: &yourub_defaults
developer_key: 'apiKey'
youtube_api_service_name: 'youtube'
youtube_api_version: 'v3'
application_name: "apiAplicationName"
application_version: "0.1"
log_level: WARN
development:
<<: *yourub_defaults
production:
<<: *yourub_defaults
test:
<<: *yourub_defaults
Restart the server. That should fix the issue.
I'm using sidekiq and twilio to send a text at a specified time.
My message_worker.rb contains the following:
class MessageWorker
include Sidekiq::Worker
sidekiq_options retry: false
sidekiq_retries_exhausted do |msg|
Sidekiq.logger.warn "Failed #{msg['class']} with #{msg['args']}: #{msg['error_message']}."
end
def perform(id)
record = Textmessage.find id
#twilio = Twilio::REST::Client.new ENV['ACCOUNT_SID'], ENV['AUTH_TOKEN']
#twilio.account.messages.create(
from: ENV['ACCOUNT_PHONE_NUMBER'],
to: record.phone_number,
body: 'This is your scheduled reminder to view a house.'
)
end
end
My redis.rb contains the following:
uri = URI.parse(ENV["REDISTOGO_URL"])
REDIS = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
I am getting the following error message (I've spaced it for ease of reading):
Completed 200 OK in 245ms (Views: 180.7ms | ActiveRecord: 46.6ms)
2014-04-21T17:...
MessageWorker JID-... INFO: fail: 0.497 sec
2014-04-21T17:04:57.636194+00:00 app[web.1]:...
WARN: {"retry"=>false, "queue"=>"default", "class"=>"MessageWorker", "args"=>[5],
"jid"=>"...", "enqueued_at"=>...}
2014-04-21T17:04:57.636194+00:00 app[web.1]: 2014-04-21T17:04:57Z 5 TID-...
**WARN: undefined method `strip' for nil:NilClass**
2014-04-21T17:04:57.637073+00:00 app[web.1]: 2014-04-21T17:04:57Z 5 TID-...
WARN: /app/vendor/bundle/ruby/2.0.0/gems/twilio-ruby-3.11.5/lib/twilio-
ruby/rest/client.rb:142: in `initialize'
I needed to set my credentials that are inside of the ENV file. The format is as follows:
heroku config:set GITHUB_USERNAME=joesmith
You can also check out heroku's information on configuration variables (config vars): config vars on heroku
I have a very strange bug which I'm in need of some clue on. Consider this:
class ApplicationController < ActionController::Base
before_filter :set_timezone
def set_timezone
if logged_in?
Time.zone = current_user.time_zone
end
end
When PayPal tries to send a notification, it comes in like so:
Started POST "/ipn_subscription_notifications" for 173.0.82.126 at 2012-03-15 04:11:45 -0400
Processing by IpnSubscriptionNotificationsController#create as HTML
Parameters: {"txn_type"=>"subscr_signup", etc...
And here it gets hung up. Ruby begins chewing up memory until the machine crashes. This is the fix:
def set_timezone
if current_user
Time.zone = current_user.time_zone
end
end
Let's look at logged_in?:
module AuthenticatedSystem
def logged_in?
current_user ? true : false
end
Which is logically equivalent to the fix.
I suspect an error is being thrown and caught, and somebody is restarting the request process. AuthenticatedSystem is certainly suspect.
This does not happen in the development environment, it throws an error and returns 500:
Started POST "/ipn_subscription_notifications" for 127.0.0.1 at 2012-03-15 15:19:39 -0700
Processing by IpnSubscriptionNotificationsController#create as */*
Parameters: {"foobar"=>nil}
Completed 500 Internal Server Error in 9ms
NoMethodError (undefined method `logged_in?' for #<IpnSubscriptionNotificationsController:0xdfdaaf4>):
app/controllers/application_controller.rb:8:in `set_timezone'
Rendered /usr/local/rvm/gems/ruby-1.9.2-p180#ce2/gems/actionpack-3.1.0/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.3ms)
Rendered /usr/local/rvm/gems/ruby-1.9.2-p180#ce2/gems/actionpack-3.1.0/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (1.0ms)
Rendered /usr/local/rvm/gems/ruby-1.9.2-p180#ce2/gems/actionpack-3.1.0/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (4.8ms)
[2012-03-15 15:19:40] ERROR Errno::ECONNRESET: Connection reset by peer
/usr/local/rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/webrick/httpserver.rb:56:in `eof?'
/usr/local/rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/webrick/httpserver.rb:56:in `run'
/usr/local/rvm/rubies/ruby-1.9.2-p180/lib/ruby/1.9.1/webrick/server.rb:183:in `block in start_thread'
Detecting such failures and handling them gracefully is my goal.
Any ideas? Can I instrument Passenger, or some other part of the Rails stack?
the error is undefined method logged_in? in your IpnSubscriptionNotificationsController, and this controller inherit from ApplicationController, are u sure include AuthenticatedSystem module in your ApplicationController, may be u can try this first
May be this does not resolve your problem, but you should use around_filter :set_timezone instead of before filter. Take a look at this: http://www.elabs.se/blog/36-working-with-time-zones-in-ruby-on-rails#working_with_multiple_user_time_zones