接下来的另一个问题(Rails 控制器 - 仅当内部的两个方法成功时才执行操作(相互依赖的方法) https://stackoverflow.com/questions/37727642/rails-controller-execute-action-only-if-the-two-methods-inside-succeed-mutual),我想确保在我的控制器操作中,如果用户没有看到 Rails UJS 方法显示的消息,则控制器操作的第一个方法也不会实现。
CONTEXT
我有一个控制器,其方法称为“操作”。当应用程序进入“example_action”方法时,它会实现第一个方法 (1) update_user_table,然后 (2) 另一个 update_userdeal_table。 (两者都会读取和写入数据库)然后 (3) 第三种方法,与 Rails UJS(ajax) 调用相关。
我的问题如下:如果控制器中间超时,我想避免更新 User 表(通过方法 1)、更新 UserDeal 表(通过方法 2)但不是第三种方法的情况即显示消息 FAILS 的 ajax 请求(错误、超时...状态如 500 或 404 或已取消或超时...)。
在我的应用程序中,对于移动用户,如果他们在有互联网连接的地铁中,他们会启动通过“example_action”控制器的请求,成功执行第一种方法 (1) 和第二种方法 (2),但随后他们进入隧道60 秒,非常非常低(
我需要两种方法(1)和(2)和(3)“相互依赖”:如果一种方法不成功,则不应执行另一种方法。这是我能描述它的最好方式。
今天这是我的代码。它不起作用,因为我通过单击手动测试,然后仅 2 秒后我就断开了互联网连接。我在数据库中看到执行了 (1) 和 (2),并且数据库已更新,但我看到消息“抱歉,花了太长时间,请重试”。
这是正确的做法吗?如果是的话该怎么做?
如果没有,我是否应该尝试不同的角度,例如:如果(1)和(2)成功但不成功(3)我是否应该存储 Rails UJS xhr 状态是错误或超时的事实,因此模态 wx 未有效显示给用户,然后在他们重新上线后向他们显示结果/消息?
这是代码
用户的 html 页面用户单击触发 Rails UJS ajax 请求的按钮,该请求最终将显示模式消息
<div id=zone">
<%= link_to image_tag(smallest_src_request),
deal_modal_path,
remote: true %>
</div>
这发送到指向此控制器操作的路由
交易控制者
class DealsController < ApplicationController
def deal_modal
Deal.transaction do
update_user_table # that's the (1)
update_userdeal_table # that's the (2)
# show_modal_message
respond_to do |format|
format.js
end
end
private
def update_user_table
# update the table User so it needs to connect to internet and acces the distant User table
end
def update_userdeal_table
# update the table UserDeal table so it needs to connect to internet and access the distant UserDeal table
end
end
这指向一个 js.erb 视图文件
deal_modal.js.erb
showModalMessage("Here is your result <variable and all>);
为了管理 ajax、错误、超时...(如果需要解决问题),我使用 Rails UJS 设置。
重要的:在这里,如果出现错误或超时,我会发送错误/超时模式消息来代替您通常收到的消息(请参见上面的“这是您的结果..”)
$(document).on('page:change', function () {
$("#zone").
on('ajax:error',function(event,xhr, status, error){
console.log(' ajax call failed:', error);
var msg;
msg = Messenger().post({
hideAfter: 4,
message: "sorry it took too long, try again."
});
});
$(document).on('page:change', function () {
//set timeout Rails UJS ajax option that will display message for ajax:error cases defined above
$.rails.ajax = function(options) {
if (!options.timeout) {
options.timeout = 5000;
}
return $.ajax(options);
};
});