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

I need a way to determine if a user entry is new or not. Based on where I need to do this in my application, I would like to do this by finding out if the user was created today or now.

How can I do something like:

if current_user.created_at.today? 

Any problems with the time zone? Maybe it would be better to do created_at in the last 24 hours?

thanks

+4
source share
5 answers

I would prefer to use current_user.created_at.to_date == Date.current , as it is more self- current_user.created_at.to_date == Date.current .

+12
source

To check if a user has been created in the last 24 hours, follow these steps:

 if current_user.created_at > Time.now - 24.hours #... end 
+8
source

you definitely have a few approaches, which is why I like rails && Rubin. In any case, do not forget about the "Law on Demeter" , so 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 you can see if the user is created today with the following api,

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

Or...

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

If your application should support time zones:

  • Verify that the correct time zone is set to config/application.rb : config.time_zone = "Mountain Time (US & Canada)"
  • Access to the current time: Time.zone.now
  • Default Time Zone Name Access: ActiveSupport::TimeZone[Rails.configuration.time_zone]
  • Get the default UTC offset for the time zone: ActiveSupport::TimeZone[Rails.configuration.time_zone].utc_offset / 1.hour
0
source

Source: https://habr.com/ru/post/1393842/


All Articles