簡體   English   中英

如何從Rails中的對象獲取創建日期?

[英]How do I get the Create date from a object in rails?

您好,我在Rails中有一個應用程序,我需要從一個對象中檢索創建日期。 我知道Rails使用時間戳自動保存此信息,並且我查看了具有Created_at信息的.json螞蟻。 問題是如何從對象訪問此信息(Created_at)(我的意圖是按創建時間排序,並顯示此信息)

謝謝你的幫助

您可以通過以下方式訪問該屬性:

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該字段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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM