how to access column value after serialization activerecord

activerecord, ruby-on-rails-3

Solution

Updated

Ok, this is what you are looking for:

User.find(params[:id]).attributes_before_type_cast["preferences"][:value]

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 = #{@user.id}")

It returns an object in the console like so:

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

Running:

preference.first[0]

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.

Problem

I have a simple model like this: ``` class User < ActiveRecord::Base serialize :preferences end ``` 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.

Original source