I have a div that I hid when a user clicks the link and shows when they click it again. We want that div to be collapsed when the user comes back if they chose to hide it so we added a boolean column hide_todo in our user database and I added a method to test the value in the user_controller. The hiding is done with jQuery and we want to change the value of hide_todo to true if the user clicks Hide and false when the user clicks Show. How would I access a Ruby variable in the application.js?
2 Answers
There are 3 ways to access ruby variables in js:
A) If you're using rails 3.1+ with asset pipeline, you can add .erb extension to the file like this: "application.js.erb". Now you can use erb tags inside .js <% ruby.code(); %> This is I would say strange way to do this and it would make sens only in special cases.
B) Usually you would add data you need to DOM of your HTML document, and retrive the data from it.
For example in your erb (or in analogical way in haml) template do sth like this:
<div id="collapsable" data-show="<%= model.hide.todo%>"> </div>
now in jQuery you can access data in following way:
hide_todo = $("#collapsable").data("show");
C) Another way is to make ajax call that will return data from the rails application.
In your case I recommend 2nd method.
display:nonewhen rendering in order to prevent content flickering. if you want to save the state of the div, you need to use ajax for this.