Domanda

I have a basic Sinatra/AJAX application that races two images against one another. The game has two users, who are both prompted to sign in upon the page load. The application is set up with an MVC framework in mind.

I am trying to implement a database that will store the results of the race. My database has three tables: games, players, and player_games (because a game can have multiple players and a player can play many games).

In the controller I have three main routes.

The POST route, which creates both players after login:

post '/' do
  @game = Game.create(player_1: params[:player1], player_2: params[:player2])
  return (@game).to_json
end

The GET '/game/:id' route, which loads the stats erb (just says the player who wins and the total time it took to play the game):

get '/game/:id' do
  @game = Game.find(params[:id])
  erb :stats
end

And the POST '/stats' route, which saves the game and the stats and redirects back to the GET request above:

post '/stats' do
  game = Game.find(params[:game_id])
  game.winner = params[:winner]
  game.play_time = params[:time]
  game.save!
  redirect '/game/' + params[:game_id]
end

In the JavaScript file, when the game is finished, I'm using jQuery's $.post method to send the stats up to the POST '/stats' route. This saves the stats, but does not redirect the game to the GET '/game/:id' route. It will totally hit the @game = Game.find(params[:id]) part of the code, and will even print "hello world" if I set up the post route like so, BUT WILL NOT REDIRECT TO THE GET '/game/:id' route:

get '/game/:id' do
  @game = Game.find(params[:id])
  erb :stats
  puts "hello world"
end

`D, [2014-04-29T19:48:51.723270 #3242] DEBUG -- :    (0.2ms)  BEGIN
D, [2014-04-29T19:48:51.729138 #3242] DEBUG -- :    (0.6ms)  UPDATE "games" SET "winner" = 'tim', "play_time" = 3, "updated_at" = '2014-04-29 19:48:51.724453' WHERE "games"."id" = 10
D, [2014-04-29T19:48:51.732144 #3242] DEBUG -- :    (2.6ms)  COMMIT
D, [2014-04-29T19:48:52.208625 #3245] DEBUG -- :   Game Load (1.4ms)  SELECT "games".* FROM "games" WHERE "games"."id" = $1 LIMIT 1  [["id", "10"]]
hello world`
È stato utile?

Soluzione

Because $.post is asynchronous, it will not redirect the page. The server code is executing, but it won't actually execute the line erb :stats.

This is kind of messy, but after your $.post, you could do window.location.href = "/game/" + whatever_the_specific_game_id_is;, and that will redirect you.

Also, be careful with your has_and_belongs_to_many join table. It should probably be named alphabetically. From ActiveRecord docs:

Unless the join table is explicitly specified as an option, it is guessed using the lexical order of the class names. So a join between Developer and Project will give the default join table name of “developers_projects” because “D” precedes “P” alphabetically.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top