简体   繁体   English

如何使用Rails序列化字段中存储的数据

[英]How to use the data stored in a rails serialized field

I have the User.guided field set to serialized in my user.rb file: 我在user.rb文件中将User.guided字段设置为序列化:

serialize :guided

In the DB the values are being stored like so: 值在数据库中的存储方式如下:

--- "{\"step1\"=>\"true\", \"step2\"=>\"false\"}"

So on my rails view I output the values to JS as so: 因此,在我的视图上,我将值输出到JS:

<script>
var guided = <%= current_user.guided.to_json.html_safe %>;
</script>

Then in the js console, guided outputs: 然后在js控制台中,引导输出:

"{"step1"=>"true", "step2"=>"false"}"

Problem is I can't access the individual values? 问题是我无法访问各个值? How do you do that? 你是怎样做的?

As guided.step1 errors with undefined 按照guided.step1错误与undefined

Thanks 谢谢

to_json returns a JSON string. to_json返回JSON字符串。 You should parse that string on the client to get the actual object. 您应该在客户端上解析该字符串以获取实际的对象。

For example: 例如:

var guided = JSON.parse(<%= current_user.guided.to_json.html_safe %>);

Also, your code doesn't return actual JSON string, but rather string with ruby hash syntax. 另外,您的代码不会返回实际的JSON字符串,而是返回具有ruby哈希语法的字符串。 There's probably more going on there than you show us. 那里发生的事情可能比您向我们展示的还要多。 This code works: 此代码有效:

obj = {"step1"=>"true", "step2"=>"false"}
obj # => {"step1"=>"true", "step2"=>"false"}
obj.to_json # => "{\"step1\":\"true\",\"step2\":\"false\"}"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM