首页 > 解决方案 > 如何在 ActionCable `subscribed` 方法中查找模型

问题描述

我已经看到很多教程用这种subscribed方法做了这样的事情:

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

这个想法是允许多个用户之间进行多次对话。但我不清楚该id参数是如何发送到该方法的。如果我的路线是嵌套的,因此对话 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'

我如何将对话 ID 传递给该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)

标签: ruby-on-railsactioncable

解决方案


这就是我解决这个问题的方法,

在我看来:

<%= 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' %>
....

注意我给表单的 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

推荐阅读