简体   繁体   中英

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

我宁愿使用current_user.created_at.to_date == Date.current ,因为它更加自我解释。

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

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

Or...

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM