3

For my Rails application I am trying to build a rake task that will populate the database with 10 invoices for each user:

def make_invoices
  User.all.each do |user|
    10.times do
      date = Date.today
      i = user.invoices.create!(:number => user.next_invoice_number,
                                :date   => date += 1.year)
      i.save
    end
  end
end

How can I increment the date by one year?

the Tin Man
  • 158,662
  • 42
  • 215
  • 303
Tintin81
  • 9,821
  • 20
  • 85
  • 178

4 Answers4

5

Change your loop to:

10.times do |t|
   puts t + 1 # will puts 1,2,3,4,5,6,7,8,9,10
end

And now you can set your year.

Matthias
  • 4,355
  • 2
  • 25
  • 34
1

Here it is using Date#next_year:

require 'date'

d = Date.today 
d # => #<Date: 2013-09-21 ((2456557j,0s,0n),+0s,2299161j)>
d.next_year # => #<Date: 2014-09-21 ((2456922j,0s,0n),+0s,2299161j)>
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
1
def make_invoices
  User.all.each do |user|
    date = Date.today
    10.times do
      user.invoices.create!(:number => user.next_invoice_number, 
                            :date   => (date += 1.year))
    end
  end
end

Because you have date = Date.today in the 10.times loop, it will be reseted in each loop. Just move date = Date.today outside the loop.

spickermann
  • 100,941
  • 9
  • 101
  • 131
1

You can take advantage of Date#next_year, which takes a parameter meaning how many years you want to advance :

def make_invoices
  User.all.each do |user|
    10.times.with_object(Date.today) do |i, date|
      user.invoices.create!(
        number: user.next_invoice_number, 
        date: date.next_year(i)
      )
    end
  end
end

Numeric#times pass an index to block.

Enumerator#with_object allow to pass additional parameters to block, which we here use to avoid setting a local variable outside the block (since we don't need it outside).

kik
  • 7,867
  • 2
  • 31
  • 32