繁体   English   中英

Ruby on rails - 如何使控制器与ajax同时执行2个动作?

[英]Ruby on rails - How to make controller execute 2 actions simultaneously with ajax?

我在开发环境中使用ajax为同一个控制器调用两个不同的操作。 在一个操作中,我正在一个非常缓慢的过程中更新数据库。 在另一个动作上,我想让百分比结束更新进度条。 我可以看到两者都在执行,问题是第二个动作正在等待第一个动作完成自己执行,它应该每秒执行一次以获得实际的百分比。 rails可以并行执行两个动作吗? 还是Webrick问题?


我按照建议尝试了puma,但它仍在等待第一个动作,继承了ajax代码调用

$(document).ready(function() {
$(':button').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: '/quotes/upload',  //Server script to process data
        type: 'POST',
        //Ajax events
        beforeSend: progress,
        success: completeHandler,
        error: function(ts) { alert(ts.responseText) },
        // Form data
        data: formData,
        //Options to tell jQuery not to process data or worry about content-type.
        cache: false,
        contentType: false,
        processData: false
    });
});
});

function progress() {
$.ajax({
    url: '/quotes/status.json',
    dataType: "JSON"
}).success(function (percentual) {
    if (percentual >= '95') {
        location.reload();
    } else {
        var $bar = $('.bar');
        $bar.width(percentual+"%");
        setInterval(progress,800);
    }
});
}

这是控制台打印输出:

Started GET "/quotes/status.json" for 127.0.0.1 at 2014-09-21 10:23:38 -0300
Processing by QuotesController#status as JSON

 percentual => 0 Completed 200 OK in 4ms (Views: 0.6ms | ActiveRecord: 0.0ms)


Started POST "/quotes/upload" for 127.0.0.1 at 2014-09-21 10:23:38 -0300
Processing by QuotesController#upload as */*
Parameters: {"quotes"=>#<ActionDispatch::Http::UploadedFile:0x00000001b980b0    @tempfile=#<Tempfile:/tmp/RackMultipart20140921-5849-otvxky>, @original_filename="HIST_XXX.TXT", @content_type="text/plain", @headers="Content-Disposition: form-data; name=\"quotes\"; filename=\"HIST_XXX.TXT\"\r\nContent-Type: text/plain\r\n">}
  Rendered quotes/index.html.erb within layouts/application (0.7ms)
 Completed 200 OK in 10456ms (Views: 170.3ms | ActiveRecord: 0.0ms)


Started GET "/quotes/status.json" for 127.0.0.1 at 2014-09-21 10:23:49 -0300
Processing by QuotesController#status as JSON

 percentual => 100 Completed 200 OK in 3ms (Views: 0.4ms | ActiveRecord: 0.0ms)

正如我在控制台上看到的那样,它只是在上传之前进行第一次通话,然后进行上传,然后在完成第二次通话之后

你是对的 - Webrick一次只能处理一个请求。 也许给ThinPumaUnicorn一个 - 他们都处理并发请求。

注意请注意,使用SQLite可能会出现类似的并发问题(特别是如果涉及写入!)切换到PostgeSQL或MySQL。


要使用Thin

的Gemfile

gem 'thin'

当然...

bundle install

然后启动服务器

thin start

使用Puma

的Gemfile

gem 'puma'

当然...

bundle install

启动服务器

rails s puma

要使用Unicorn

的Gemfile

gem 'unicorn'

当然...

bundle install

启动服务器

unicorn_rails

感谢您的提示,我找到了一个解决方案:将它放在您的development.rb文件中:

config.middleware.delete Rack::Lock

你还必须改变Webrick。 它与Puma一起工作正常。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM