Rails, ¿cómo determinar si se creó un usuario hoy?

I would like a way to determine if a User record is new or not. Based on where I need to do this in my app, I would like to do this by know if the user was created today or now.

¿Cómo puedo hacer algo como:

if current_user.created_at.today?

Any timezone issues? Maybe it would be better to do, created_at in the last 24 hours?

Muchas Gracias

preguntado el 30 de enero de 12 a las 19:01

Is your requirement for the server side to know if it was created today or the user in their local time? Timezone would matter in the later case. -

5 Respuestas

Prefiero usar current_user.created_at.to_date == Date.current, as it is more self explanatory.

Respondido 02 Abr '13, 23:04

To check if the user was created in the last 24 hours, do something like this:

if current_user.created_at > Time.now - 24.hours

Respondido el 30 de enero de 12 a las 23:01

-24.hours isn't going to work as that could take you into yesterday, instead use: Time.now.beginning_of_day - rana gorda

you definitely have several approaches, this is also why I like rails && ruby. Anyway don't forget about Ley de Deméter, hence I will go with the following:

class User
  # ... methods and other active record stuff

  def created_today?
    self.created_at.to_date == Date.today


and than you can see if a user is created today with the following api,

 if User.find(params[:id]).created_today?
   #do something...

contestado el 02 de mayo de 13 a las 22:05


 scope :today, lambda {
   where('authdate = ?', Date.today )

Respondido el 30 de enero de 12 a las 23:01

If your application needs to support time zones:

  • Ensure you have the correct time zone set in config/application.rb: config.time_zone = "Mountain Time (US & Canada)"
  • Access the current time: Time.zone.now
  • Access the name of the default time zone: ActiveSupport::TimeZone[Rails.configuration.time_zone]
  • Retrieve the UTC offset for the default time zone: ActiveSupport::TimeZone[Rails.configuration.time_zone].utc_offset / 1.hour

Respondido el 30 de enero de 12 a las 23:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.