ActionCable с использованием переменной контроллера - PullRequest
0 голосов
/ 24 сентября 2018

В моем проекте Ruby on Rails у меня есть модель user, настроенная devise.Каждый user принадлежит account с account_id.

В моем application_controller.rb у меня есть

def set_account
  @account = current_user.account
end

Это работает нормально, так как во многих местах моего проекта у меня есть before_action: set_account, и он правильно назначает @account.

Когда пользователь входит в систему, я хочу, чтобы пользователь подписался на message_notifications_channel_#{account_id}, где account_id - это идентификатор учетной записи, к которой принадлежит пользователь.

Вот как я настраиваю 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 verified_user = User.find_by(id: cookies.encrypted[:user_id])
      verified_user
    else
      reject_unauthorized_connection
    end
  end
end

end

Когда я вошел сюда через buug, User.find_by(id: cookies.encrypted[:user_id]) вернул ноль и cookies.encrypted[:user_id] тоже ноль.

Это настройка для message_notifications_channel.rb:

class MessageNotificationsChannel < ApplicationCable::Channel
  def subscribed
    current_user.appear
    # stream_from "some_channel"
    stream_from "message_notifications_channel_#{params[:account_id]}"
  end

  def unsubscribed
    current_user.disappear
    # Any cleanup needed when channel is unsubscribed
  end
end

Для message_notifications.coffee, это код:

App.message_notifications = App.cable.subscriptions.create {channel: "MessageNotificationsChannel", account_id: current_user.account_id},
  connected: ->
    # Called when the subscription is ready for use on the server

  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
    if data['direction'] == 'incoming'
      ding = new Audio('/assets/ding.wav');
      ding.play();
      $('#conversation-messages').append String(data['message']);
    if data['direction'] == 'outgoing'
      if $('#message_'+data['id']).length == 0
        iphone_sms_sent_sound = new Audio('/assets/iphone_send_sms.mp3');
        iphone_sms_sent_sound.play();
        $('#conversation-messages').append String(data['message']);
      else
        $('#message_'+data['id']).replaceWith(data['message']);

Я использую следующеедля широковещательного сообщения в after_create обратном вызове Message.rb:

ActionCable.server.broadcast "message_notifications_channel_#{self.account_id}", {id: self.id, direction: self.direction, message: ApplicationController.render(partial:'inbox/message', locals: {message: self})}

Это не будет работать, и я получил «Несанкционированная попытка подключения была отклонена».Я попытался использовать App.message_notifications = App.cable.subscriptions.create {channel: "MessageNotificationsChannel", account_id: @account.id} Это также не будет работать.Затем я сделал App.message_notifications = App.cable.subscriptions.create {channel: "MessageNotificationsChannel", account_id: 3} и закомментировал current_user.appear и current_user.disappear в message_notifications_channel.rb и все внутри

module ApplicationCable
end

в файле connection.rb.Затем пакеты будут транслироваться и приниматься, и все будет отображаться.

Как заставить App.message_notifications = App.cable.subscriptions.create {channel: "MessageNotificationsChannel", account_id: }, использовать идентификатор @account.id или current_user.account_id при сохранении методов проверки пользователя в connection.rb?Спасибо!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...