如何序列化ActiveRecord的访问后列的值 [英] how to access column value after serialization activerecord

查看:140
本文介绍了如何序列化ActiveRecord的访问后列的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样一个简单的模型:

I have a simple model like this:

class User < ActiveRecord::Base
  serialize :preferences
end

我想从MySQL访问原始值,而不是序列化前的值。这可能吗?

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

我知道我可以使用

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

不过,我想从用户访问模式。

推荐答案

更新

好吧,这是你在找什么:

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.

旧答案

只是要知道我理解的问题,你想从表中的原始数据。该导轨序列化,并把数据库中的数据。

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。你把 ['SITE_ID','LAST_UPDATE','last_restart'] ,你会得到--- \正SITE_ID \正LAST_UPDATE \正last_restart \ N,它被放在数据库并保存。要检索的:--- \正SITE_ID \正LAST_UPDATE \正last_restart \ N从数据库

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.

好吧,这花了一些fanagaling从数据库中,但你可以做到这一点,像这样。

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

在一个项目中,我有一个序列化的阵列呼叫 devise_table_ preferences ,列出了preferences在一个表中的某个特定的顺序显示,如下所示:

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> 

运行:

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.

这篇关于如何序列化ActiveRecord的访问后列的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆