如何在Rails中创建Action Cable连接。

huangapple go评论83阅读模式
英文:

how to create action cable connection in rails

问题

module ApplicationCable
  class Connection < ActionCable::Connection::Base

    identified_by :current_user

    def connect
      self.current_user = find_verified_user
      logger.add_tags "ActionCable","User #{current_user.id}"
    end

    def find_verified_user
      if current_user = env['wardon'].user
        current_user
      else
        reject_unauthorized_connection
      end
    end
  end
end
英文:
module ApplicationCable
  class Connection < ActionCable::Connection::Base

    identified_by :current_user

    def connect
      self.current_user = find_verified_user
      logger.add_tags "ActionCable","User #{current_user.id}"
    end

    def find_varified_user
      if current_user = env['wardon'].user
        current_user
      else
        reject_unauthorized_connection
      end
    end
  end
end

答案1

得分: 3

首先,生成一个通道:

rails g channel {通道名称} {你将发送的操作}

这将在 "app/channels" 文件夹中生成通道。

然后,在 routes.rb 中挂载通道:

# config/routes.rb
# 添加这一行
mount ActionCable.server => '/cable'

接下来,从客户端应用程序订阅该通道并使用你在通道中创建的方法。

你可以查看这个教程 使用 Rails Action Cable 创建聊天

但请忽略客户端部分。

英文:

first, you generate a channel

rails g channel {channel_name} {the action you will send to}

this will generate the channel in "app/channels" folder

then mount the channel in routes.rb

  #config/routes.rb
     # add this line
   mount ActionCable.server => '/cable'

then you subscribe to the channel from your client app and use the method you've created in your channel

you can review this tutorial
Create Chat Using Action Cable

but ignore the client-side part

huangapple
  • 本文由 发表于 2020年1月3日 20:40:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/59578832.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定