Last Updated: February 25, 2016
·
1.011K
· swillis16

From Rails Controller to Javascript

Ever had to send some information from your Rails controller to your javascript? If so then you've probably had to add a pesky Javascript tag into your erb or HAML in order to get the information though. I recently cam across a gem called Gon from a RailsCast which allows a more direct way to send data from controller to Javascript. Simply include the gem in your Gemfile:

gem 'gon'

then toss

<%= include_gon %>

into the title of your application.html.[erb || haml] and now you can access the 'gon' variable within your controller and its associated js.coffee file. It is also recommended that you always check iof the gon variable is set within your Coffeescript before you use it.

Thanks to RailsCasts for creating a great intro to Gon, and I hope that it can be of use to someone.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip