When you are dealing with an SJR template that just isn’t working it can be the most frustrating thing in the world. It can seem like no matter what you put into that js.erb file, the resulting JS shows no life whatsoever. You spend days trying to figure out the problem, and no solutions are working. Worst of all, there are usually no error messages to guide your debugging or make sense of the behavior you are seeing. Sometimes you get to the point where it just isn’t worth it anymore, and you have to give up and move on.
Luckily most issues in an SJR template fall into one of three categories. Once you learn to identify the type of error you are dealing with, debugging becomes much simpler.
Learn about each one below never feel helpless when encountering a broken SJR template ever again!
Errors in your Ruby code
Ruby Runtime Errors are ones that you are already familiar with from your other Ruby code and are the easiest to spot and debug.
When embedded Ruby (found within
<%= %> tags when using ERB) causes one of these errors, the entire request will fail.
This turns out to be a good thing because Rails “fails loudly” and lets you know all about it in a couple of ways.
First, the Rails server log will print an error message along with a stack trace that points to the offending line in the SJR template.
You can also spot the error by using your web browser’s developer debugging tools. There will typically be an alert or error message in the console that lets you know that the result of the AJAX request was a failure (500 server error). You can even inspect the body of the response in the XHRs section and will show you the standard Rails error page.
Error message in browser debugging console
Response body showing Ruby error
Now instead of just failing silently, the browser debugging tools will show helpful error messages and stacktraces just like our Ruby runtime errors!
If you’ve eliminated runtime errors as the cause of your broken SJR template, see if it’s a syntax error instead by trying the following:
Check the response body in the debugging tools. Does it look syntactically correct? Does it have proper syntax highlighting and spacing?
Replace embedded Ruby with static strings.
This will help you identify if your ERB calls are the culprit.
No more aimless debugging