如何访问 Rails 5 Action Cable Channels 中的关注点和应用程序控制器代码

5 sockets ruby-on-rails ruby-on-rails-5 actioncable

我有一些我想从 Action Cable Channel 调用的代码。

假设我有通知渠道,我想打电话更新一些

values 并且它确实调用了该方法,但它没有调用另一个方法

写在应用程序控制器中。

说,

在我的 channel.rb 中,我正在使用:

class NotificationsChannel < ApplicationCable::Channel
  include NotificationChannel

 def some_method
  create_notification(current_user, quiz)
 end
end
Run Code Online (Sandbox Code Playgroud)

NotificationChannel 问题代码:

module NotificationChannel
  extend ActiveSupport::Concern

  def create_notification(is_current_user, resource)
    teacher_user_id = resource.lesson_plan.teacher.user_id
    Notification.create(description: "A user with name #{get_user_name(is_current_user)} has liked the  #{resource.title}", user_id: teacher_user_id, url: resource_misc_path(resource, "quiz_notification_like_check"))
  end
end
Run Code Online (Sandbox Code Playgroud)

现在,

第一个问题:

该方法get_user_name(is_current_user)在关注点和

它写在ApplicationController.

第二个问题:

resource_misc_path(resource, "quiz_notification_like_check" is written in some helper it does not call even helper method.
Run Code Online (Sandbox Code Playgroud)

PS:我也注意到在 Channel.rb 中具有_path_url不可访问的路由

任何合适的解决方法?

Jen*_*eni 0

关于这个主题有一些非常有用的答案:How do I get current_user in ActionCablerails-5-api app?

最重要的是,在 Cable 中没有会话,因此您无法真正使用会话方法。

您必须直接使用 cookie 重写它们。

正如 @Sajan 在他的回答中所说:“websocket 服务器没有会话,但它可以读取与主应用程序相同的 cookie。”