I am using Rails 3.1, it seems that I could not use Ruby script after a CoffeeScript statement in my create_error.js.coffee view file for the AJAX response.
If I do it like this it will work:
<% if @attached_image.errors.any? %>
alert 'something is wrong'
<% end %>
but if it is like the following, with a <% %> after the CoffeeScript statement,
errors_block = '<div id="errors_block"></div>'
<% if @attached_image.errors.any? %>
something..
<% end %>
I will alway get an exception of ActionView::Template::Error (Parse error on line 6: Unexpected 'INDENT') on the if line. I’ve tried several samples, everytime it happens when a ruby <% %> comes after a coffeescript statement.
Why is that?
Sounds like you’re running into indentation issues in your post-ERB CoffeeScript. Given this:
The output will look like this when the
ifcondition is true:and that indentation starts a new block that doesn’t make sense in that context; hence the “Unexpected ‘INDENT'” error from the CoffeeScript compiler. You can see this in action in this snippet on coffeescript.org.
CoffeeScript is very sensitive to indentation so mixing ERB and CoffeeScript like that isn’t a good idea. You’d be better off putting
@attached_image.errorsinto a CoffeeScript variable and then doing the logic in CoffeeScript, something more like this (untested code):The JSON version of the errors array should be valid CoffeeScript so
errorswill be a CoffeeScript array. Theto_ais there in caseerrorsreturnsnil, I’m not sure off the top of my head iferrors.nil?is possible but a little extra paranoia never hurt anyone.You could also do this:
but that’s harder to read and you will forget. You’re better off using ERB to generate CoffeeScript data and letting CoffeeScript handle the logic.