Showing posts with label rails3. Show all posts
Showing posts with label rails3. Show all posts

Tuesday, March 5, 2013

JavaScript in Rails 3.2

After struggling to get CoffeeScript running correctly in my current Rails app, I decided to try using plain-ol' JavaScript and everything worked like a charm. CoffeeScript is very cool (don't get me wrong), however, setting it up is a painful and poorly documented process that proved (in my case) to be fruitless. Anyhow, I though it might be helpful to document how simple it is to get normal JavaScript working on a Rails app.

Firstly, enter the following line in the view that needs JavaScript code:
    <%= javascript_include_tag "my_js_file" %>

This line ensures that my_js_file.js is included in the current view (note that in the "include tag" the ".js" is omitted).

Secondly,  simply code/add your JavaScript file to /app/assets/javascripts/. It will now be available in your view!

I am somewhat conflicted as to how valuable this modus operandi is (there are a few good articles arguing about the benefits of using CoffeeScript); however, at the current moment it is the best solution I have found. If you know any tips about linking CoffeeScript to Rails, please comment below!