【问题标题】:Convert ActiveRecord array serialized attribute to string将 ActiveRecord 数组序列化属性转换为字符串
【发布时间】:2018-01-25 18:34:53
【问题描述】:

我正在开发一个 Rails 3.2 应用程序,它使用 ActiveRecord's serialize method 以这种方式以数组的形式存储模型属性:

serialize :bucket, Array

我想删除那个序列化并且只存储一个字符串。问题是当我这样做时,我会以这种方式存储一个字符串:

ruby [62] pry(main)> bucket.inspect => "\"---\\n- something something\\n\""

如何将该字符串清除为 something something ?我尝试使用正则表达式,但无法形成正确的匹配器。这是我最接近的尝试:

bucket.scan(/\---\\n- (.*?)\\n/)

【问题讨论】:

  • bucket存储前的值是多少?
  • @rantingsonrails ['something something']

标签: ruby-on-rails ruby regex activerecord


【解决方案1】:

如果您查看该方法的来源,您会发现由于Array 不会同时响应:load:dump,它最终使用Coders::YAMLColumn 将数据存储为细绳。因此,如果您不再希望以这种方式对其进行序列化,您可以使用该类将load 的数据从字符串中返回到Array,然后将数组重组为您选择的字符串。你也可以只使用YAML,因为Coders::YAMLColumn 似乎只是用一些类型检查来包装它:

require 'yaml'
# this should be the value of bucket if you don't inspect it
array = YAML.load("---\n- something something\n") 
# => ["something something"]
array.join(' ') # or first or join with whatever else, deal with it how you want
# => "something something"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多