0

您好,我在 Rails 中有一个应用程序,我需要从对象中检索创建日期。我知道 Rails 使用时间戳来自动保存此信息,并且我查看了具有 Created_at 信息的 .json 蚂蚁。问题是我如何从对象访问此信息(Created_at)(我的意图是按创建时间排序,并显示这个)

感谢任何帮助

4

1 回答 1

1

您可以通过以下方式访问该属性:

u = User.first   # Let's pretend there's a `User` model within the rails application. Here im getting the first record and storing that user in the variable `u`.

u[:created_at]  # This will give me the value for the `created_at`, for instance: Thu, 18 Oct 2012 14:42:44 UTC +00:00 

or

u.created_at  # will give you the same result

如果您想sort通过该字段,您可以(例如假设有User模型)使用sort_by

User.all.sort_by &:created_at  # This is just a demonstration, you might want to get a sub-set of whatever model you're querying with `where` and some relevant criteria.

或者

   User.find(:all, :order => "created_at")  # old and deprecated approach

或者

   User.order("created_at DESC") #  more recent approach
于 2013-04-20T16:46:46.703 回答