我有一个Web应用程序,我需要在其中执行需要一段时间才能完成的过程(通常需要1分钟)。
我将尝试简要地解释一下:在我的应用程序中,我有一个算法,该算法基于一堆参数(主要是日期)将外键分配给一组对象。当用户按下应用程序内的指定按钮时,将执行控制器方法。在该方法内部,我调用模型中的一种方法,在该方法中处理了所有逻辑并分配了键。如前所述,整个过程大约需要一分钟才能完成。
所以我的问题是:在Rails 5中在后台运行此过程的最佳方法是什么?我显然不想强迫我的用户等待一分钟,然后他们才能浏览应用程序,我也不希望浏览器在等待服务器响应时应用程序超时。那么解决这个问题的最佳方法是什么?我需要一个可以异步发出请求的框架吗?如果是这样,哪一个?(如果它不需要太多的依赖关系并且我可以继续使用ActiveRecord,我会更喜欢)。
我在ActionCable或AJAX方面并没有做太多工作,但是如果他们能以任何方式完成工作,那么我会很高兴知道如何做。
理想情况下,完成该过程后,我应该能够在应用内向用户发送通知
view.html.erb:
# Button the user presses to execute the algorithm
<%= link_to 'execute algorithm', algorithm_path(@variable), :method => :put %>
Run Code Online (Sandbox Code Playgroud)
my_controller.rb:
def button_method
Object.execute_algorithm(@variable)
redirect_to :back
end
Run Code Online (Sandbox Code Playgroud)
Object.rb:
def self.execute_algorithm(variable)
# Logic
end
Run Code Online (Sandbox Code Playgroud) 我的应用程序中有2个用户类型(工作人员和公司)。两种用户类型都是通过Devise创建的。我目前正在尝试使用ActionCable向特定公司发送通知。
我的主要问题是,当我发送通知时,每个登录的公司都会收到该通知。我知道应该以某种方式在流名称中包含公司ID,但到目前为止我还没有碰到任何运气。
我已经包含了向以下所有公司发送通知的工作代码:
notifications_channel.rb
class NotificationsChannel < ApplicationCable::Channel
def subscribed
stream_from "notifications_channel"
end
def unsubscribed
# Any cleanup needed when channel is unsubscribed
end
end
Run Code Online (Sandbox Code Playgroud)
connection.rb
module ApplicationCable
class Connection < ActionCable::Connection::Base
end
end
Run Code Online (Sandbox Code Playgroud)
呼叫广播
ActionCable.server.broadcast 'notifications_channel', { 'My data' }
Run Code Online (Sandbox Code Playgroud)
编辑
我使用javascript记录了通知的状态:
notifications.js
App.notifications = App.cable.subscriptions.create("NotificationsChannel", {
connected: function() {
console.log("connected");
};
disconnected: function() {
console.log("disconnected");
};
received: function(data) {
console.log("recieved");
};
});
Run Code Online (Sandbox Code Playgroud)