Rails控制器未完全执行

时间:2019-01-06 22:42:09

标签: ruby-on-rails

从2个不同的javascript函数执行相同的ajax代码。在这两个函数中,ajax都将调用控制器中的connected函数来更新Room表中的值。但是,当从javascript函数connected调用ajax时,将执行整个函数,而不是从disconnected调用该函数。

show.html.erb中的JavaScript函数

var room_id = <%= @room.id %>
console.log("room id: ", room_id)

  session.on("connectionCreated", function(event) {
      console.log("connectionCreated");
       $.ajax({
                type: "PUT",
                data: JSON.stringify({ room: {connected: true}, _method:'put' }),
                url: "/rooms/" + room_id + "/connected",
                contentType: 'application/json'
              }).done(function( msg ){
                alert( "Data Saved: " + msg );
       });
   });

  // Disconnect
  session.on('sessionDisconnected', function(event) {
    console.log("session Disconnected")
    $.ajax({
            type: "PUT",
            data: JSON.stringify({ room: {connected: false}, _method:'put' }),
            url: "/rooms/" + room_id + "/connected",
            contentType: 'application/json'
            }).done(function( msg ){
                alert( "Data Saved: " + msg );
       });
    window.location.replace('<%= rooms_path %>');
  });
}

Server.logs:

 From: 

/Users/us186007/Desktop/WebApps/goldenyears/app/controllers/rooms_controller.rb @第38行Rooms RoomsController#connected:

36: def connected
37:     binding.pry
=> 38:     @room = Room.find params[:room_id]
39:     binding.pry
40:     @room.update_attributes(:connected => params[:room][:connected])
41: end

 [1] pry(#<RoomsController>)> continue
Room Load (0.4ms)  SELECT  "rooms".* FROM "rooms" WHERE "rooms"."id" = $1 
LIMIT $2  [["id", 6], ["LIMIT", 1]]

From: /Users/us186007/Desktop/WebApps/goldenyears/app/controllers/rooms_controller.rb @ line 40 RoomsController#connected:

36: def connected
37:     binding.pry
38:     @room = Room.find params[:room_id]
39:     binding.pry
=> 40:     @room.update_attributes(:connected => params[:room][:connected])
41: end

[1]撬(#)>继续    (0.2ms)开始    (0.2ms)提交     找不到用于RoomsController#connected的模板,渲染头:no_content     在20108ms中完成204没内容(ActiveRecord:0.8ms)

  Started PUT "/rooms/6/connected" for 127.0.0.1 at 2019-01-06 13:33:31 -0800
 Processing by RoomsController#connected as */*
Parameters: {"room"=>{"connected"=>false}, "room_id"=>"6"}
Started GET "/rooms" for 127.0.0.1 at 2019-01-06 13:33:31 -0800

From: /Users/us186007/Desktop/WebApps/goldenyears/app/controllers/rooms_controller.rb @ line 38 RoomsController#connected:

36: def connected
37:     binding.pry
=> 38:     @room = Room.find params[:room_id]
39:     binding.pry
40:     @room.update_attributes(:connected => params[:room][:connected])
41: end

即使服务器日志显示从connectedCreated函数中调用它时,它已达到sessoinDisconected。 如何理解发生了什么?服务器日志中没有错误消息。

1 个答案:

答案 0 :(得分:0)

我解决了。这是因为行:window.location.replace('<%= rooms_path %>');。在完全执行控制器代码之前,它将重定向到rooms_path。我将重定向代码移至done的{​​{1}}部分。