AnApprentice
AnApprentice

Reputation: 110960

Rails, how to determine if a user was created today?

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.

How can I do something like:

if current_user.created_at.today?

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

Thanks

Upvotes: 4

Views: 4229

Answers (5)

user171910
user171910

Reputation:

you definitely have several approaches, this is also why I like rails && ruby. Anyway don't forget about Demeter Law, 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
  end

end

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

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

Upvotes: 4

Pedro Nascimento
Pedro Nascimento

Reputation: 13886

I'd rather use current_user.created_at.to_date == Date.current, as it is more self explanatory.

Upvotes: 13

Graham Swan
Graham Swan

Reputation: 4828

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

Upvotes: 0

simonmorley
simonmorley

Reputation: 2804

Or...

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

Upvotes: 0

Marek Příhoda
Marek Příhoda

Reputation: 11198

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
  #...
end

Upvotes: 8

Related Questions