1

I'm making an AJAX call in my rails app using the move action. The controller action reads:

def move
    @game = Game.find_by_id(params[:game])
    @player_square = params[:square].to_i
    @game.move(@player_square, :player)
    @ai_square = GameKeeper.ai_move(@game)
    @game.move(@ai_square, :ai) unless @game.squares.compact.count == 9
    @winner = GameKeeper.winner(@game) || "" # need to convert nil to an empty string because javascript recognizes null, not nil

end

and my move.js.erb contains:

var ai_square = $("#square_<%= @ai_square %>");
ai_square.after("X");
ai_square.remove();
var player_square = $("#square_<%= @player_square %>");
player_square.after("O");
player_square.remove();

if(<%= @winner %>) {
     $('#winner').slideToggle("slow");
}

If I comment out the if block in the javascript, the other code works properly, but if the if stays in, the js doesn't execute regardless of whether or not @winner is truthy. What could be going wrong?

Solution

So for whatever reason, if you switch out the js if block with an erb if block, like so

<% if @winner %>
    $("#winner").slideToggle("slow");
<% end %>

everything works fine! It'd be nice to know why the original version didn't work, but here's a solution if anyone else out there is having the same problem.

  • Do you need to add a `respond_to do` block to your action? You might need to specify `format.js`. This [Stackoverflow](http://stackoverflow.com/questions/9492362/rails-how-does-the-respond-to-block-work) answer might help. – claptimes May 21 '13 at 19:31
  • If using chrome, check your console for errors and also inspect the response in the Network tab, and try to run it in the console as well. – omarvelous May 21 '13 at 20:06
  • @claptimes I tried `respond_to` before, and by the server log it's definitely executing the move.js.erb file whether I add the block or not. If I comment out the if block the js runs fine. @omarvelous there's no errors in the console and if I run the if block in the console using the string literals @winner is set to in the controller it works fine! Maybe there's a problem with the erb injection? Thanks very much to both of you for helping out a noob! – Matt Rieger May 22 '13 at 14:32

0 Answers0