Reputation: 110960
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
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
Reputation: 13886
I'd rather use current_user.created_at.to_date == Date.current
, as it is more self explanatory.
Upvotes: 13
Reputation: 4828
If your application needs to support time zones:
config/application.rb
: config.time_zone = "Mountain Time (US & Canada)"
Time.zone.now
ActiveSupport::TimeZone[Rails.configuration.time_zone]
ActiveSupport::TimeZone[Rails.configuration.time_zone].utc_offset / 1.hour
Upvotes: 0
Reputation: 2804
Or...
scope :today, lambda {
where('authdate = ?', Date.today )
}
Upvotes: 0
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