How do I save data on LocalStorage in Ruby on Rails 3.2.8?

后端 未结 4 940
走了就别回头了
走了就别回头了 2021-01-02 10:42

I\'m trying to save a variable called persistent_data.

I usually use session[:persistent_data] or cookies[:persistent_data], b

相关标签:
4条回答
  • 2021-01-02 11:09

    well this is quite simple and need to understand how local storage works.

    You can do that directly or (and this is probably cleaner) use the setItem() and getItem() method:

    localStorage.setItem('color','blue');
    

    If you read out the color key, you will get back “blue”:

    localStorage.getItem('color');`// output will be blue`
    

    To remove the item, you can use the removeItem() method:

    localStorage.removeItem('color');
    

    annoying thing is when you have an array, it will not be stored the right way.

    var car = {};
    car.wheels = 4;
    car.doors = 2;
    car.sound = 'vroom';
    car.name = 'Suzuki Mehran';
    console.log( car );
    localStorage.setItem( 'car', car );
    console.log( localStorage.getItem( 'car' ) ); //output as `[object Object]`
    

    but no need to worry we have a solution for that too.. You can work around this by using the native JSON.stringify() and JSON.parse() methods:

    localStorage.setItem( 'car', JSON.stringify(car) );
    

    and you can get it back by simply

    JSON.parse( localStorage.getItem( car ) );
    

    hope you have not any confusion now !!!

    0 讨论(0)
  • 2021-01-02 11:13

    As far as I know localStorage has nothing to do with Rails, it is pure Javascript/HTML5 feature.

    You can use the following in you application js in order to read or write data from the local storage:

    var foo = localStorage.getItem("bar");
    localStorage.setItem("bar", foo);
    
    0 讨论(0)
  • 2021-01-02 11:13

    As others have already said local storage is Javascript/Html feature/solution but if wanting to learn how to integrate that with rails Ryan Bates has a railscast at http://railscasts.com/episodes/248-offline-apps-part-2, though you might need to watch part 1 to fully understand it.

    0 讨论(0)
  • 2021-01-02 11:32

    Localstorage has nothing to do with rails. You do it the same way as with any other language:

    <script>
    localStorage.setItem("company_id", "1");
    </script>
    
    localStorage.getItem("company_id");
    => 1
    

    You can use rails to dynamically set the item however:

    <script>
    localStorage.setItem("company_id", "<%= @company.id %>");
    </script>
    
    0 讨论(0)
提交回复
热议问题