Skip to content Skip to sidebar Skip to footer

How Can I Set A Session Variable From A Js Inside Haml In Ruby On Rails?

I have table row shading (for groups of row) via js. I want to make it so that the shading is remembered through a session variable. The haml partial I am using has: Group Shading:

Solution 1:

You can't use erb statements within javascript, it is parsed before it is send to a client. Instead use javascript sessionStorage:

$(function(){
$("a#row_colors_on").click(function(){
$(".row_color_group_1").addClass("color_group_1");
$(".row_color_group_2").addClass("color_group_2");
$(".row_color_group_3").addClass("color_group_3");
sessionStore.setItem('group_shading', true);
event.preventDefault();
});
});
$(function(){
$("a#row_colors_off").click(function(){
$(".row_color_group_1").removeClass("color_group_1");
$(".row_color_group_2").removeClass("color_group_2");
$(".row_color_group_3").removeClass("color_group_3");
sessionStorage.setItem('group_shading', false);
});
});

$(document).ready(function() {
  if (sessionStorage.getItem('group_shading'))
    $("a#row_colors_on").click();
});

Important note:

Note however that js session is sth else than your rails session. Rails session can be stored in various places and javascript has no access to it. This means you can't access those values on the server side. There are two solutions:

1) Use sessionStorage and execute some javascript depending on stored value after the page has loaded (as above).

2) Instead of using sessionStorage, send an ajax request to server to populate rails session (recommended).

Solution 2:

You can share state between Javascript (client-side) and Rails (server-side) with cookies. You can set a cookie in the view via Javascript (check out the js-cookie library), and read the cookies in a Rails controller.

Using the js-cookie library, you could set a cookie: (Cookie.set('awesome', 'sauce')) and then read it in the Rails controller: (puts cookies['awesome']).

Post a Comment for "How Can I Set A Session Variable From A Js Inside Haml In Ruby On Rails?"