如何获取数据库中原始的“created_at”值(不是转换为ActiveSupport :: TimeWithZone的对象) [英] How to get the raw 'created_at' value in the database (not an object cast to an ActiveSupport::TimeWithZone)

查看:712
本文介绍了如何获取数据库中原始的“created_at”值(不是转换为ActiveSupport :: TimeWithZone的对象)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想象一下我有一个Post模型。



,数据库中的一条记录为:

  title_here | content_here | 2011-02-20 08:01:55.583222 | 2011-02-20 08:01:55.583222 


$ b b

且最后两个字段( 2011-02-20 08:01:55.583222 | 2011-02-20 08:01:55.583222 )是created_at和updated_at领域。



然后,

  post = Post.find_by_id b $ b  

问题:如何获取created_at字符串:

如我们所知,post.created_at将返回数据库中的

a ActiveSupport :: TimeWithZone 对象,而不是原始字符串。



请帮助:)

解决方案

use attributes_before_type_cast

  Post.find(23).attributes_before_type_cast [created_at] 

  Post.find(23).read_attribute_before_type_cast(created_at)

编辑



您也可以这样调用:

  Post.find(23).created_at_before_type_cast 

根据在类型转换之前访问属性链接。


Imagine I have a Post Model.

and one record in the database will be:

23|title_here|content_here|2011-02-20 08:01:55.583222|2011-02-20 08:01:55.583222

and the last two field (2011-02-20 08:01:55.583222|2011-02-20 08:01:55.583222 ) are the created_at and updated_at field.

Then,

post = Post.find_by_id(23)

Question: How can I get the created_at string: "2011-02-20 08:01:55.583222" in the data base?

As we know, the post.created_at will return a ActiveSupport::TimeWithZone object, not the raw string.

Please help :)

解决方案

use attributes_before_type_cast

Post.find(23).attributes_before_type_cast["created_at"]

or

Post.find(23).read_attribute_before_type_cast("created_at")

Edit

You can call like this also:

Post.find(23).created_at_before_type_cast

according to Accessing attributes before they have been typecasted link.

这篇关于如何获取数据库中原始的“created_at”值(不是转换为ActiveSupport :: TimeWithZone的对象)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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