Reputation: 3006
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
?
Upvotes: 0
Views: 800
Reputation: 3006
Well we ended up using $.get('toggle_hide');
, adding a method to the controller to toggle the boolean and mapping that to the resources in route.rb
. Thanks for the suggestions though!
Upvotes: 0
Reputation: 5504
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.
Upvotes: 2