как найти модель в ActionCable `метод подписки` - PullRequest
1 голос
/ 27 марта 2020

Я видел, что многие учебники делают что-то подобное с методом subscribed:

class MessagesChannel < ApplicationCable::Channel
 def subscribed
  conversation = Conversation.find(params[:id])
  stream_from "conversation_#{conversation.id}"
 end
end

Идея состоит в том, чтобы разрешить несколько разговоров между несколькими пользователями. Но я не понимаю, как этот id параметр отправляется в метод. Если мои маршруты вложены так, что идентификатор разговора находится в URL, похоже, что должно работать.

resources :conversations, only: [:index, :create] do
 resources :messages, only: [:index, :create]
end

Однако вышеприведенный код канала выдает эту ошибку:

[ActionCable] [user] Registered connection (Z2lkOi8vZnJhY3Rpb25jbHViL1VzZXIvMQ)
[ActionCable] [user] Could not execute command from ({"command"=>"subscribe", "identifier"=>"{\"channel\":\"MessagesChannel\"}"}) [ActiveRecord::RecordNotFound - Couldn't find Conversation without an ID]: /Users/user/.rvm/gems/ruby-2.5.0/gems/activerecord-5.2.0/lib/active_record/relation/finder_methods.rb:431:in `find_with_ids' | /Users/user/.rvm/gems/ruby-2.5.0/gems/activerecord-5.2.0/lib/active_record/relation/finder_methods.rb:69:in `find' | /Users/user/.rvm/gems/ruby-2.5.0/gems/activerecord-5.2.0/lib/active_record/querying.rb:5:in `find' | /Users/user/.rvm/gems/ruby-2.5.0/gems/activerecord-5.2.0/lib/active_record/core.rb:167:in `find' | /Users/user/code/project/app/channels/messages_channel.rb:3:in `subscribed'

Как передать идентификатор беседы методу subscribed, чтобы мои пользователи могли иметь несколько личных бесед?


Обновление 1: Это мой messages.coffee файл

App.messages = App.cable.subscriptions.create
 channel: "MessagesChannel"
 conversation_id: 1

 connected: ->
  console.log 'Connected'

 disconnected: ->
  console.log 'Disconnected'

 received: (data) ->
  console.log 'Received'
  $('#messages').append(data.message)

 speak: (message, conversation_id) ->
  @perform 'speak', message: message, conversation_id: conversation_id

$(document).on 'turbolinks:load', ->
 submit_message()
 scroll_bottom()

submit_message = () ->
 $('#response').on 'keydown', (event) ->
  if event.keyCode is 13
   App.messages.speak(event.target.value)
   event.target.value = ""
   event.preventDefault()

scroll_bottom = () ->
 $('#messages').scrollTop($('#messages')[0].scrollHeight)

1 Ответ

1 голос
/ 27 марта 2020

Вот как я справляюсь с этим,

В моей форме просмотра:

<%= form_for Message.new,remote: true,html: {id: 'new-message',multipart: true} do |f| %>
          <%= f.hidden_field :chat_id, value: chat.id,id: 'chat-id' %>
....

Обратите внимание на идентификатор, который я дал для формы, а затем на поле chat_id.

Тогда в моем chat.js:

return App.chat = App.cable.subscriptions.create({
      channel: "ChatChannel",
      chat_id: $('#new-message').find('#chat-id').val()
    }

Теперь я могу использовать этот chat_id параметр в моем ChatChannel следующим образом:

def subscribed
  stream_from "chat_#{params['chat_id']}_channel"
end

РЕДАКТИРОВАТЬ:

В вашем случае:

ваше подписанное на MessagesChannel действие должно быть таким:

def subscribed
 stream_from "conversation_#{params[:conversation_id]}"
end
...