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

萝らか妹 提交于 2019-12-08 23:54:47

问题


I'm trying to save a variable called persistent_data.

I usually use session[:persistent_data] or cookies[:persistent_data], but I would like to use the localstorage instead.

How do I do that on Rails?


回答1:


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>



回答2:


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);



回答3:


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.




回答4:


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 !!!



来源:https://stackoverflow.com/questions/12806198/how-do-i-save-data-on-localstorage-in-ruby-on-rails-3-2-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!