how to access column value after serialization activerecord

I have a simple model like this:

class User < ActiveRecord::Base
  serialize :preferences

I want to access the raw value from mysql, not value before serialize. Is it possible?

I know I can use

ActiveRecord::Base.connection.execute("select * from users")

But I want to access from the User model.



Ok, this is what you are looking for:


This will return the string in its serialized form.

That is the closest you can get that I can find, it won't work if you have already gotten the object pulled from the database.

Sorry for misreading your question. You can use this from the User model too.

Leaving the old answer up just in case the other way of doing it is helpful to someone.

Old Answer

Just to be sure I understand the question, you want the raw data from the table. The data that rails serializes and puts in the database.

EX. You put in ['site_id','last_update','last_restart'] and you get "---\n- site_id\n- last_update\n- last_restart\n" and it is put in the database and saved. You want to retrieve this: "---\n- site_id\n- last_update\n- last_restart\n" from the database.

Ok, it took some fanagaling from the database but you can do it like so.

In a project I have a serialized array call devise_table_preferences that lists the preferences to display in a table in a particular order, like so:

user.devise_table_preferences = ['site_id','last_update','last_restart']

The serialized view of it is like so:

"---\n- site_id\n- last_update\n- last_restart\n"

Using your method above, I made a query like so:

preference = ActiveRecord::Base.connection.execute("SELECT devise_table_preferences FROM users WHERE id = #{}")

It returns an object in the console like so:

preference = #<Mysql2::Result:0x007fe4cdf34850> 



Gave me this:

"---\n- site_id\n- last_restart\n"

I know its a big work around but it will definitely give you your data in its serialized way. Hope that it helps you out.

I think these days you want to say the following:


attributes_before_type_cast didn't work for me.


This works even if the object is loaded.

Need Your Help

What is C# 'internal' in

c# syntax keyword

What is C# internal keyword equivalent in VB.NET?

Hibernate, Postgres & Array Type

java arrays postgresql hibernate

I'm stuck on a specific issue using array type in postgresql 9.3 mapped with hibernate 4.1.0.