How to get the raw 'created_at' value in the database (not an object cast to an ActiveSupport::TimeWithZone)

不羁岁月 提交于 2019-12-03 23:19:39

问题


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 :)


回答1:


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.




回答2:


Try

Post.find_by_id(23).created_at.to_s


来源:https://stackoverflow.com/questions/5056447/how-to-get-the-raw-created-at-value-in-the-database-not-an-object-cast-to-an

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