Serializing Rails with a Default Value and New Objects

Another rail serialization . I read a lot of them and could not find the answer to my problem, and so here:

I have a typical:

class User < ActiveRecord::Base serialize :prefs, Hash 

In my migrations (thanks this question + answer):

 add_column :user, :prefs, :text, default: { foo: 'bar' }.to_yaml 

Now when I load an existing user: prefs gets deserialized:

 User.first.prefs[:foo] # returns 'bar' User.first.prefs.class # returns Hash User.first.prefs # returns {:foo => "bar"} 

So it works great! But when I create a new one:

 User.new.prefs[:foor] # TypeError: can't convert Symbol into Integer User.new.prefs.class # returns String User.new.prefs # returns "---\n:foo: bar\n" 

Is it possible to get this job without any of them?

I really want to make it work only with the default database. Am I doing something wrong?

+4
source share
2 answers

I never found out what led to the behavior of this behavior, but everything works with Rails 3.2.13. Using serialize :prefs, Hash :

 [1] pry(main)> User.new => #<User id: nil, prefs: {:foo=>"bar"}, created_at: nil, updated_at: nil> [2] pry(main)> User.new.prefs => {:foo=>"bar"} 

And using store :prefs, accessors: [:foo] :

 [1] pry(main)> User.new => #<User id: nil, prefs: {:foo=>"bar"}, created_at: nil, updated_at: nil> [2] pry(main)> User.new.foo => "bar" 

My migration:

 add_column :user, :prefs, :text, default: { foo: 'bar' }.to_yaml 
+1
source

When I did the following in the Rails console (Rails 3.2.6, Ruby 1.9.3-p194):

 u=User.new(:prefs=>{:foo2=>"bar2"}) 

I returned:

 => #<User id: nil, name: nil, prefs: {:foo2=>"bar2"}, created_at: nil, updated_at: nil> 

So, I think this is the syntax you want.

+1
source

All Articles