简体   繁体   English

Rails Console中的数据库值为[“”,“ 5”,“ 1”,“ 2”,“ 8”,“ 6”,“ 9”],显示为“ [\\” \\”,\\“ 5 \\”, \\“ 1 \\”,\\“ 2 \\”,\\“ 8 \\”,\\“ 6 \\”,\\“ 9 \\”]“?

[英]Database value is [“”, “5”, “1”, “2”, “8”, “6”, “9”] in Rails Console is showing as “[\”\“, \”5\“, \”1\“, \”2\“, \”8\“, \”6\“, \”9\“]”?

Database value is 数据库值为

["", "5", "1", "2", "8", "6", "9"] 

But in Rails console it showing as: 但是在Rails控制台中,它显示为:

"[\"\", \"5\", \"1\", \"2\", \"8\", \"6\", \"9\"]" 

Any solution to show it as same as the array? 任何解决方案,以显示它与数组相同?

Looks like you column is saved as json 看起来您的列已另存为json

[15] pry(main)> JSON.parse("[\"\", \"5\", \"1\", \"2\", \"8\", \"6\", \"9\"]")
=> ["", "5", "1", "2", "8", "6", "9"]

you can use serialize :name_of_that_column, Array so it get parsed when called from db 您可以使用serialize :name_of_that_column, Array以便从数据库调用时对其进行解析

you can check http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html f 您可以检查http://api.rubyonrails.org/classes/ActiveRecord/AttributeMethods/Serialization/ClassMethods.html f

If what you want do is getting array of integers from string, use scan and regular expression. 如果要从字符串中获取整数数组,请使用scan和正则表达式。

For example, 例如,

   pry(main)> str = "[\"\", \"5\", \"1\", \"2\", \"8\", \"6\", \"9\"]"
    => "[\"\", \"5\", \"1\", \"2\", \"8\", \"6\", \"9\"]"
   pry(main)> str.scan(/\d+/)
    => ["5", "1", "2", "8", "6", "9"]

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

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