ruby-on-rails - 如何在 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)
解决方案
这就是我解决这个问题的方法,
在我看来:
<%= 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
推荐阅读
- r - 定义具有重叠和连接时间间隔的展示时段/剧集
- c - 重新定义在 C 中作为参数传递的结构有什么用?
- c++ - 为什么在 C++ 中将有符号字符分配给无符号字符时从 256 中减去?
- reactjs - 我可以在 reactjs PWA 上制作可离线使用的 PDF 文件吗?
- android - 可以在 Android Studio 中使用 Profiler 而不将其附加到特定应用程序吗?
- sql - 使用来自其他表和外键的数据进行 SQL 更新
- elasticsearch - Elasticsearch _search 不提供结果
- css - 混合背景图像的平面颜色
- wordpress - 如何在产品页面上添加类别列表(WooCommerce)
- arkit - FBX 在 Reality Converter 中导出模型的纹理平铺问题