Yves Medhard Tibe-bi
Yves Medhard Tibe-bi

Reputation: 33

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

Hello I have an app in rails and i need to retrive the create date from an object. I know that rails use timestamps to automatically save this info, and i looked at the .json ant it have the Created_at info. The question is how do i access this info (Created_at) from the object ( my intention is order by create time, and show this too)

Tks to any help

Upvotes: 0

Views: 201

Answers (1)

fmendez
fmendez

Reputation: 7338

You can access that property in the following way:

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

If you want to sort by that field, you could (following the assumption that there's a User model for instance) use the 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.

Or

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

Or

   User.order("created_at DESC") #  more recent approach

Upvotes: 1

Related Questions