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.