开发者

Rails Seralized My Object One Way & Refuses to Change

开发者 https://www.devze.com 2022-12-21 02:38 出处:网络
I have a rails class that serializes one attribute. class Statistic < ActiveRecord::Base serialize :userlist

I have a rails class that serializes one attribute.

class Statistic < ActiveRecord::Base

serialize :userlist

end

When a statistic object is loaded and it's userlist changed from a String to an Array userlist always gets serialized back into a String. The framework seems to remember and deserialize :userlist into a String even if it went in as an Array.

>> s = Statistic.find 238
=> #<Statistic id: 238, userlist: "--- \n- 2222437\n- \"99779\"\n- \"120429\"\n- \"210503\"\n- 32...">
# Note here: :userlist is an Array in YAML. Why doesn't it get correctly deserialized?

>> s.userlist.class
=> String
>> s.userlist = s.userlist.split(/\s+/)

>> s.userlist.class
=> Array

>> s.save
=> true

>> s.reload
=> #<Statistic id: 238,userlist: "--- \n- 2222437\n- \"9977开发者_JS百科9\"\n- \"120429\"\n- \"210503\"\n- 32...">

>> s.userlist.class
=> String

The goal of this exercise is to convert all String userlists to Array. If I change the class (serialize :userlist, Array) before converting I get TypeMismatch exceptions.

ActiveRecord::SerializationTypeMismatch: userlist was supposed to be a Array, but was a String

Is there a way to force AR to interpret userlist as an Array?

% rails --version
Rails 2.3.4


Is there a particular reason you're not using a regular association for this?

To answer the question, IIRC you can pass the class_name to serialize.

serialize :userlist, :class_name => 'Array'

Alternatively try:

serialize :userlist, Array

I hope this helps!


Found the problem. The String is not correct YAML:

>> YAML::load(s.userlist)
ArgumentError: syntax error:ScannerException while scanning a quoted scalar we had this found unexpected end of stream
        from (irb):8

The code from AR::B is

      def object_from_yaml(string)
        return string unless string.is_a?(String) && string =~ /^---/
        YAML::load(string) rescue string
      end

Some of the data were longer than 65,535 characters long, overflowing the mysql text column.

0

精彩评论

暂无评论...
验证码 换一张
取 消