how to access column value after serialization activerecord

痞子三分冷 提交于 2019-12-13 12:54:59

问题


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.


回答1:


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.




回答2:


I think these days you want to say the following:

User.find(params[:id]).typecasted_attribute_value('preferences')




回答3:


attributes_before_type_cast didn't work for me.

User.first.instance_variable_get(:@attributes)['preferences'].serialized_value

This works even if the object is loaded.



来源:https://stackoverflow.com/questions/11036563/how-to-access-column-value-after-serialization-activerecord

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!