我将ActionCable与rails一起使用来创建实时通知。在ApplicationCable :: Connection中的connect方法被执行,但是在客户端的连接回调不是!
这些是我的文件:
app / channels / connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
identified_by :current_user
def connect
self.current_user = find_verified_user
end
private
def find_verified_user
if current_user = User.last
current_user
else
reject_unauthorized_connection
end
end
end
end
app / channels / order_channel.rb
class OrderChannel < ApplicationCable::Channel
def subscribed
stream_from "order_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
def speak_m(data)
ActionCable.server.broadcast('order_channel', data)
end
end
app / assets / javascripts / cable.js
// Action Cable provides the framework to deal with WebSockets in Rails.
// You can generate new channels where WebSocket features live using the `rails generate channel` command.
//
//= require action_cable
//= require_self
//= require_tree ./channels
(function() {
this.App || (this.App = {});
App.cable = ActionCable.createConsumer();
}).call(this);
app / assets / javascripts / cable / subscriptions / order.coffee
App.order = App.cable.subscriptions.create "OrderChannel",
connected: ->
@speak_m()
# Called when the subscription is ready for use on the server
disconnected: ->
alert 'disconnected disconnected 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
alert data
speak_m: ->
@perform("speak_m", 'My Message!!')
config / application.rb
require_relative 'boot'
require 'rails/all'
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
Bundler.require(*Rails.groups)
module Web
class Application < Rails::Application
# Initialize configuration defaults for originally generated Rails version.
config.load_defaults 5.1
config.action_cable.mount_path = '/cable'
# Settings in config/environments/* take precedence over those specified here.
# Application configuration should go into files in config/initializers
# -- all .rb files in that directory are automatically loaded.
end
end
config / cable.yml
development:
adapter: async
test:
adapter: async
我在布局中添加了<%= action_cable_meta_tag %>
并将mount ActionCable.server => '/cable'
添加到route.rb
我正在使用: -红宝石2.3 -导轨5.1.4 -彪马3.7 -postgres 9.6
我正在使用docker