NoMethodError – undefined method `safe_constantize’ for nil:NilClass
我正在尝试按照 GoRails.com 上的 actioncable 指南创建一个 ActionCable 聊天室。
当我尝试连接到 ActionCable 时,我收到以下错误:
NoMethodError – nil:NilClass
的未定义方法”safe_constantize”
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
[ActionCable] [User 1] Could not execute command from
{“command”=>“subscribe”,“identifier”=>“ {“ChatroomsChannel“:”ChatroomsChannel“,”room_id“:1}”}) [NoMethodError – undefined method `safe_constantize’ for nil:NilClass]: /Users/Mathias/.rvm/gems/ruby- 2.2.3@chatroomv1/gems/actioncable- 5.0.0.rc2/lib/action_cable/connection/subscriptions.rb:29:in `add‘ | /Users/Mathias/.rvm/gems/ruby-2.2.3@chatroomv1/gems/actioncable- 5.0.0.rc2/lib/action_cable/connection/subscriptions.rb:15:in `execute_command’ | /Users/Mathias/.rvm/gems/ruby– 2.2.3@chatroomv1/gems/actioncable– 5.0.0.rc2/lib/action_cable/connection/base.rb:88:in `dispatch_websocket_message’ | /Users/Mathias/.rvm/gems/ruby- 2.2.3@chatroomv1/gems/actioncable- 5.0.0.rc2/lib/action_cable/server/worker.rb:54:in `block in invoke‘ | /Users/Mathias/.rvm/gems/ruby-2.2.3@chatroomv1/gems/actioncable- 5.0.0.rc2/lib/action_cable/server/worker.rb:39:in `block in work’ |
我的 app/channels/chatrooms_channel.rb 看起来像这样:
1
2 3 4 5 6 7 |
def subscribed
@chatroom = Chatroom.find(params[:room_id]) #puts params[:room_id] #current_user.join_room(@chatroom) stream_from“chatrooms:#{@chatroom.id}” # stream_from”some_channel” end |
也许值得一提的是我从 rails 4 升级到 rails 5.0.0.rc2。
谢谢你,
- 不熟悉 action_cable,但它似乎期望 channel 作为频道名称的键,而不是像你那样的 ChatroomsChannel。
在 assets/javascripts/channels/chatroom.coffee
如果你需要分配params,频道名称也必须在params hash中:
1
2 3 4 5 6 7 |
App[‘chatroom’ + roomId] = App.cable.subscriptions.create {
channel: ‘ChatroomChannel’, room_id: roomId }, { received: -> … } |
而且只有在不需要params的情况下,才可以写出不带hash的频道名:
1
2 3 |
App.chatroom = App.cable.subscriptions.create ‘ChatroomChannel’,
received: -> … |
来源:https://www.codenong.com/39131726/