Best way to create random DateTime in Rails

前端 未结 12 1997
粉色の甜心
粉色の甜心 2020-12-22 23:49

What is the best way to generate a random DateTime in Ruby/Rails? Trying to create a nice seeds.rb file. Going to use it like so:

 Foo.create(name: Faker::Lo         


        
12条回答
  •  梦毁少年i
    2020-12-23 00:23

    Here is how to create a date in the last 10 years:

    rand(10.years).ago
    

    You can also get a date in the future:

    rand(10.years).from_now
    

    Update – Rails 4.1+

    Rails 4.1 has deprecated the implicit conversion from Numeric => seconds when you call .ago, which the above code depends on. See Rails PR #12389 for more information about this. To avoid a deprecation warning in Rails 4.1 you need to do an explicit conversion to seconds, like so:

    rand(10.years).seconds.ago
    

提交回复
热议问题